rsa v1
A Go package that provides a simple and secure interface for RSA key generation, management, and PEM encoding/decoding.
Repository
Installation
go get -u github.com/metadiv-io/rsa
Features
Generate RSA key pairs with customizable bit sizes (minimum 1024 bits)
Convenient 4096-bit key generation for long-term security
PEM encoding/decoding for both public and private keys
Type-safe key handling with separate PublicKey and PrivateKey types
Usage
Generating New Keys
// Generate a 4096-bit RSA key (recommended for long-term security)
privateKey := rsa.New4096RSAKey()
// Or generate a custom-sized key (minimum 1024 bits)
privateKey, err := rsa.NewRSAKey(2048)
if err != nil {
// Handle error
}
Working with Keys
// Get the public key from a private key
publicKey := privateKey.PublicKey()
// Get key sizes
privateBits := privateKey.Size() // Returns size in bits
publicBytes := publicKey.Size() // Returns size in bytes
// Export keys as PEM strings
privatePEM := privateKey.Pem()
publicPEM := publicKey.Pem()
Loading Keys from PEM
// Load a private key from PEM
privateKey, err := rsa.NewPrivateKeyFromPem(pemString)
if err != nil {
// Handle error
}
// Load a public key from PEM
publicKey, err := rsa.NewPublicKeyFromPem(pemString)
if err != nil {
// Handle error
}
Error Handling
The package provides several error types for specific validation scenarios:
ErrInvalidBitSize
: Returned when the requested key size is not positive or not a multiple of 8ErrBitSizeTooSmall
: Returned when the requested key size is less than 1024 bitsErrInvalidPEM
: Returned when parsing an invalid PEM-encoded public keyErrNotRSAPublicKey
: Returned when the parsed key is not an RSA public keyErrInvalidPrivateKeyPEM
: Returned when parsing an invalid PEM-encoded private keyErrInvalidPrivateKey
: Returned when the parsed private key is invalid
Security Recommendations
Use 4096-bit keys (
New4096RSAKey()
) for long-term security beyond 2030Never share private keys or store them in plaintext
Always use secure random number generation (handled automatically by this package)
Keep your Go version updated to ensure you have the latest security patches
Last updated