Documentation
¶
Overview ¶
Package rsa provides RSA public-key cryptography.
This package implements RSA encryption and digital signatures with support for multiple key sizes, PKCS1v15 and OAEP padding schemes, and PEM format key storage.
Features ¶
- RSA key pair generation (2048, 3072, 4096 bits)
- PKCS1v15 and OAEP encryption/decryption
- Digital signatures with PSS padding
- PEM/PKCS1/PKCS8 format support
- SSH public key format conversion
Basic Example ¶
keyPair := &rsa.KeyPair{}
err := keyPair.Generate(2048)
ciphertext, _ := keyPair.EncryptOAEP("secret")
plaintext, _ := keyPair.DecryptOAEP(ciphertext)
Package rsa provides rsa crypto related implementations.
Package rsa provides rsa crypto related implementations.
Index ¶
- type KeyPair
- func (kp *KeyPair) DecryptOAEP(ciphertext []byte) (string, error)
- func (kp *KeyPair) DecryptPKCS1v15(ciphertext []byte) (string, error)
- func (kp *KeyPair) EncryptOAEP(plaintext string) ([]byte, error)
- func (kp *KeyPair) EncryptPKCS1v15(plaintext string) ([]byte, error)
- func (kp *KeyPair) Generate(bits int) error
- func (kp *KeyPair) GetKeyPair() (privateKey PrivateKey, publicKey PublicKey)
- func (kp *KeyPair) SetKeyPair(privateKey PrivateKey, publicKey PublicKey)
- type PrivateKey
- func (pk *PrivateKey) DecryptOAEP(ciphertext []byte) (string, error)
- func (pk *PrivateKey) DecryptPKCS1v15(ciphertext []byte) (string, error)
- func (pk *PrivateKey) EncryptOAEP(plaintext string) ([]byte, error)
- func (pk *PrivateKey) EncryptPKCS1v15(plaintext string) ([]byte, error)
- func (pk *PrivateKey) Get() *rsa.PrivateKey
- func (pk *PrivateKey) GetPemPKCS1() string
- func (pk *PrivateKey) GetPemPKCS8() (string, error)
- func (pk *PrivateKey) GetPublicKey() PublicKey
- func (pk *PrivateKey) Set(privateKey *rsa.PrivateKey)
- func (pk *PrivateKey) SetBits(bits int) error
- func (pk *PrivateKey) SetPemPKCS1(pemPKCS1 string) error
- func (pk *PrivateKey) SetPemPKCS8(pemPKCS8 string) error
- type PublicKey
- func (pk *PublicKey) EncryptOAEP(plaintext string) ([]byte, error)
- func (pk *PublicKey) EncryptPKCS1v15(plaintext string) ([]byte, error)
- func (pk *PublicKey) Get() rsa.PublicKey
- func (pk *PublicKey) GetPemPKCS1() string
- func (pk *PublicKey) GetPemPKIX() (string, error)
- func (pk *PublicKey) GetSsh() (string, error)
- func (pk *PublicKey) GetSshPublicKey() (ssh.PublicKey, error)
- func (pk *PublicKey) Set(publicKey rsa.PublicKey)
- func (pk *PublicKey) SetPemPKCS1(pemPKCS1 string) error
- func (pk *PublicKey) SetPemPKIX(pemPKIX string) error
- func (pk *PublicKey) SetSsh(sshKey string) error
- func (pk *PublicKey) SetSshPublicKey(publicKey ssh.PublicKey) error
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type KeyPair ¶
type KeyPair struct {
// contains filtered or unexported fields
}
KeyPair provides RSA key pair operations.
func (*KeyPair) DecryptOAEP ¶
DecryptOAEP decrypts ciphertext using OAEP padding (recommended).
Parameters ¶
- ciphertext: Encrypted data
Returns ¶
- string: Decrypted plaintext
- error: Error if decryption fails, nil on success
Examples ¶
plaintext, err := keyPair.DecryptOAEP(ciphertext)
func (*KeyPair) DecryptPKCS1v15 ¶
DecryptPKCS1v15 decrypts ciphertext using PKCS#1 v1.5 padding.
Parameters ¶
- ciphertext: Encrypted data
Returns ¶
- string: Decrypted plaintext
- error: Error if decryption fails, nil on success
Examples ¶
plaintext, err := keyPair.DecryptPKCS1v15(ciphertext)
func (*KeyPair) EncryptOAEP ¶
EncryptOAEP encrypts plaintext using OAEP padding (recommended).
Parameters ¶
- plaintext: Text to encrypt
Returns ¶
- []byte: Encrypted ciphertext
- error: Error if encryption fails, nil on success
Examples ¶
ciphertext, err := keyPair.EncryptOAEP("secret message")
func (*KeyPair) EncryptPKCS1v15 ¶
EncryptPKCS1v15 encrypts plaintext using PKCS#1 v1.5 padding.
Parameters ¶
- plaintext: Text to encrypt
Returns ¶
- []byte: Encrypted ciphertext
- error: Error if encryption fails, nil on success
Examples ¶
ciphertext, err := keyPair.EncryptPKCS1v15("secret message")
func (*KeyPair) Generate ¶
Generate creates a new RSA key pair.
Parameters ¶
- bits: Key size in bits (2048, 3072, or 4096 recommended)
Returns ¶
- error: Error if generation fails, nil on success
Examples ¶
keyPair := &rsa.KeyPair{}
err := keyPair.Generate(2048)
func (*KeyPair) GetKeyPair ¶
func (kp *KeyPair) GetKeyPair() (privateKey PrivateKey, publicKey PublicKey)
GetKeyPair retrieves the private and public keys.
Returns ¶
- privateKey: RSA private key
- publicKey: RSA public key
Examples ¶
privateKey, publicKey := keyPair.GetKeyPair()
func (*KeyPair) SetKeyPair ¶
func (kp *KeyPair) SetKeyPair(privateKey PrivateKey, publicKey PublicKey)
SetKeyPair sets the private and public keys.
Parameters ¶
- privateKey: RSA private key
- publicKey: RSA public key
Examples ¶
keyPair.SetKeyPair(privateKey, publicKey)
type PrivateKey ¶
type PrivateKey struct {
// contains filtered or unexported fields
}
PrivateKey is struct that provides private key related methods.
func (*PrivateKey) DecryptOAEP ¶
func (pk *PrivateKey) DecryptOAEP(ciphertext []byte) (string, error)
DecryptOAEP decrypts ciphertext using OAEP padding.
This method decrypts data that was encrypted with the corresponding public key using OAEP padding. OAEP is the recommended padding scheme for RSA encryption due to its strong security properties. Uses SHA-256 for hashing.
Parameters:
- ciphertext: The encrypted data to decrypt
Returns:
- string: The decrypted plaintext
- error: Error if decryption fails or ciphertext is invalid
Behavior:
- Ciphertext must match the key size (e.g., 256 bytes for 2048-bit key)
- Provides protection against chosen-ciphertext attacks
- Automatically validates padding during decryption
Example:
plaintext, err := privateKey.DecryptOAEP(ciphertext)
if err != nil {
log.Fatal(err)
}
fmt.Println("Decrypted:", plaintext)
func (*PrivateKey) DecryptPKCS1v15 ¶
func (pk *PrivateKey) DecryptPKCS1v15(ciphertext []byte) (string, error)
DecryptPKCS1v15 decrypts ciphertext using PKCS#1 v1.5 padding.
This method decrypts data that was encrypted with the corresponding public key using PKCS#1 v1.5 padding. This padding scheme has known vulnerabilities and should only be used for compatibility with legacy systems.
Parameters:
- ciphertext: The encrypted data to decrypt
Returns:
- string: The decrypted plaintext
- error: Error if decryption fails or ciphertext is invalid
Behavior:
- Ciphertext must match the key size (e.g., 256 bytes for 2048-bit key)
- Vulnerable to padding oracle attacks in some scenarios
- Consider using DecryptOAEP for new applications
Example:
plaintext, err := privateKey.DecryptPKCS1v15(ciphertext)
if err != nil {
log.Fatal(err)
}
fmt.Println("Decrypted:", plaintext)
func (*PrivateKey) EncryptOAEP ¶
func (pk *PrivateKey) EncryptOAEP(plaintext string) ([]byte, error)
EncryptOAEP encrypts plaintext using the public key with OAEP padding.
This method uses Optimal Asymmetric Encryption Padding (OAEP), which provides better security than PKCS#1 v1.5. OAEP is the recommended padding scheme for RSA encryption in new applications. Uses SHA-256 for hashing.
Parameters:
- plaintext: The string to encrypt
Returns:
- []byte: The encrypted ciphertext
- error: Error if encryption fails or plaintext is too long
Behavior:
- Maximum plaintext size = key_size - 2*hash_size - 2 (e.g., 190 bytes for 2048-bit key with SHA-256)
- Provides provable security against chosen-ciphertext attacks
- Non-deterministic (same plaintext produces different ciphertext)
Example:
privateKey := &rsa.PrivateKey{}
privateKey.SetBits(2048)
ciphertext, err := privateKey.EncryptOAEP("confidential data")
if err != nil {
log.Fatal(err)
}
func (*PrivateKey) EncryptPKCS1v15 ¶
func (pk *PrivateKey) EncryptPKCS1v15(plaintext string) ([]byte, error)
EncryptPKCS1v15 encrypts plaintext using the public key with PKCS#1 v1.5 padding.
This method uses the public key portion of the private key to encrypt data. PKCS#1 v1.5 padding is a legacy scheme and should be avoided for new applications. Use EncryptOAEP instead for better security.
Parameters:
- plaintext: The string to encrypt
Returns:
- []byte: The encrypted ciphertext
- error: Error if encryption fails or plaintext is too long
Behavior:
- Maximum plaintext size depends on key size and padding overhead
- Uses cryptographically secure random padding
- Same plaintext produces different ciphertext each time (non-deterministic)
Example:
privateKey := &rsa.PrivateKey{}
privateKey.SetBits(2048)
ciphertext, err := privateKey.EncryptPKCS1v15("secret message")
if err != nil {
log.Fatal(err)
}
func (*PrivateKey) Get ¶
func (pk *PrivateKey) Get() *rsa.PrivateKey
Get returns the underlying *rsa.PrivateKey.
This method provides direct access to the Go standard library rsa.PrivateKey for use with other crypto functions that require the native type.
Returns:
- *rsa.PrivateKey: The underlying private key
Example:
nativeKey := privateKey.Get() // Use with Go crypto functions x509.MarshalPKCS1PrivateKey(nativeKey)
func (*PrivateKey) GetPemPKCS1 ¶
func (pk *PrivateKey) GetPemPKCS1() string
GetPemPKCS1 encodes the private key as a PEM-encoded PKCS#1 string.
PKCS#1 is the traditional RSA private key format. The PEM encoding allows the key to be stored in text files or transmitted as text. The format uses "RSA PRIVATE KEY" as the PEM block type.
Returns:
- string: PEM-encoded PKCS#1 private key
Behavior:
- Output format: "-----BEGIN RSA PRIVATE KEY-----\n...\n-----END RSA PRIVATE KEY-----"
- This format is RSA-specific (not algorithm-agnostic)
- Widely supported but less flexible than PKCS#8
Example:
pemString := privateKey.GetPemPKCS1()
os.WriteFile("private_key.pem", []byte(pemString), 0600)
func (*PrivateKey) GetPemPKCS8 ¶
func (pk *PrivateKey) GetPemPKCS8() (string, error)
GetPemPKCS8 encodes the private key as a PEM-encoded PKCS#8 string.
PKCS#8 is a more flexible, algorithm-agnostic private key format that can represent keys from various algorithms (RSA, ECDSA, Ed25519, etc.). This is the preferred format for modern applications.
Returns:
- string: PEM-encoded PKCS#8 private key
- error: Error if encoding fails
Behavior:
- Output format: "-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----"
- Algorithm-agnostic format (stores algorithm identifier)
- Better interoperability with other systems
Example:
pemString, err := privateKey.GetPemPKCS8()
if err != nil {
log.Fatal(err)
}
os.WriteFile("private_key_pkcs8.pem", []byte(pemString), 0600)
func (*PrivateKey) GetPublicKey ¶
func (pk *PrivateKey) GetPublicKey() PublicKey
GetPublicKey extracts the public key from the private key.
Every RSA private key contains the corresponding public key. This method creates a PublicKey instance containing the public key portion.
Returns:
- PublicKey: The corresponding public key
Behavior:
- The public key is derived from the private key's N and E values
- The returned public key can be safely shared with others
- Useful for creating matched key pairs for encryption/decryption
Example:
privateKey := &rsa.PrivateKey{}
privateKey.SetBits(2048)
publicKey := privateKey.GetPublicKey()
// Share publicKey with others for encryption
func (*PrivateKey) Set ¶
func (pk *PrivateKey) Set(privateKey *rsa.PrivateKey)
Set assigns an existing *rsa.PrivateKey to this PrivateKey instance.
This method allows setting the private key from an existing Go standard library rsa.PrivateKey, useful when loading keys from other sources or libraries.
Parameters:
- privateKey: The rsa.PrivateKey to assign
Example:
nativeKey, _ := rsa.GenerateKey(rand.Reader, 2048)
privateKey := &rsa.PrivateKey{}
privateKey.Set(nativeKey)
func (*PrivateKey) SetBits ¶
func (pk *PrivateKey) SetBits(bits int) error
SetBits generates a new RSA private key with the specified bit size.
This is a convenience method that generates a new key pair and sets it as the current private key. Common bit sizes are 2048, 3072, and 4096.
Parameters:
- bits: The size of the key in bits (recommended: 2048 minimum, 3072+ for sensitive data)
Returns:
- error: Error if key generation fails
Behavior:
- Generates both private and public keys
- Uses cryptographically secure random number generator
- Larger key sizes provide more security but slower operations
Example:
privateKey := &rsa.PrivateKey{}
err := privateKey.SetBits(2048)
if err != nil {
log.Fatal(err)
}
func (*PrivateKey) SetPemPKCS1 ¶
func (pk *PrivateKey) SetPemPKCS1(pemPKCS1 string) error
SetPemPKCS1 loads a private key from a PEM-encoded PKCS#1 string.
This method decodes a PEM-encoded PKCS#1 private key and sets it as the current private key. The input should have the "RSA PRIVATE KEY" PEM block type.
Parameters:
- pemPKCS1: PEM-encoded PKCS#1 private key string
Returns:
- error: Error if decoding fails or format is invalid
Behavior:
- Expects "-----BEGIN RSA PRIVATE KEY-----" header
- Validates the RSA key structure
- Replaces the current key if successful
Example:
pemData, _ := os.ReadFile("private_key.pem")
privateKey := &rsa.PrivateKey{}
err := privateKey.SetPemPKCS1(string(pemData))
if err != nil {
log.Fatal(err)
}
func (*PrivateKey) SetPemPKCS8 ¶
func (pk *PrivateKey) SetPemPKCS8(pemPKCS8 string) error
SetPemPKCS8 loads a private key from a PEM-encoded PKCS#8 string.
This method decodes a PEM-encoded PKCS#8 private key and sets it as the current private key. PKCS#8 is the algorithm-agnostic format that can represent various key types.
Parameters:
- pemPKCS8: PEM-encoded PKCS#8 private key string
Returns:
- error: Error if decoding fails or key is not RSA
Behavior:
- Expects "-----BEGIN PRIVATE KEY-----" header
- Automatically identifies RSA algorithm from key data
- Type assertion ensures the key is RSA
Example:
pemData, _ := os.ReadFile("private_key_pkcs8.pem")
privateKey := &rsa.PrivateKey{}
err := privateKey.SetPemPKCS8(string(pemData))
if err != nil {
log.Fatal(err)
}
type PublicKey ¶
type PublicKey struct {
// contains filtered or unexported fields
}
PublicKey is struct that provides public key related methods.
func (*PublicKey) EncryptOAEP ¶
EncryptOAEP encrypts plaintext using OAEP padding (recommended).
This method uses Optimal Asymmetric Encryption Padding (OAEP) with SHA-256, which provides better security than PKCS#1 v1.5. This is the recommended padding scheme for RSA encryption.
Parameters:
- plaintext: The string to encrypt
Returns:
- []byte: The encrypted ciphertext
- error: Error if encryption fails or plaintext is too long
Behavior:
- Maximum plaintext size = key_size - 2*hash_size - 2 (e.g., 190 bytes for 2048-bit key)
- Provides provable security against chosen-ciphertext attacks
- Non-deterministic encryption
Example:
publicKey := &rsa.PublicKey{}
// ... load public key ...
ciphertext, err := publicKey.EncryptOAEP("confidential data")
if err != nil {
log.Fatal(err)
}
func (*PublicKey) EncryptPKCS1v15 ¶
EncryptPKCS1v15 encrypts plaintext using PKCS#1 v1.5 padding.
This method encrypts data with the public key using PKCS#1 v1.5 padding. This padding scheme is legacy and has known vulnerabilities. Use EncryptOAEP for new applications.
Parameters:
- plaintext: The string to encrypt
Returns:
- []byte: The encrypted ciphertext
- error: Error if encryption fails or plaintext is too long
Behavior:
- Maximum plaintext size depends on key size (e.g., ~245 bytes for 2048-bit key)
- Same plaintext produces different ciphertext each time
- Only the corresponding private key can decrypt
Example:
publicKey := &rsa.PublicKey{}
// ... load public key ...
ciphertext, err := publicKey.EncryptPKCS1v15("secret message")
if err != nil {
log.Fatal(err)
}
func (*PublicKey) Get ¶
Get returns the underlying rsa.PublicKey.
This method provides direct access to the Go standard library rsa.PublicKey for use with other crypto functions that require the native type.
Returns:
- rsa.PublicKey: The underlying public key (returned by value)
Example:
nativeKey := publicKey.Get() // Use with Go crypto functions x509.MarshalPKIXPublicKey(&nativeKey)
func (*PublicKey) GetPemPKCS1 ¶
GetPemPKCS1 encodes the public key as a PEM-encoded PKCS#1 string.
PKCS#1 is the traditional RSA public key format. The PEM encoding allows the key to be stored in text files. The format uses "RSA PUBLIC KEY" as the PEM block type.
Returns:
- string: PEM-encoded PKCS#1 public key
Behavior:
- Output format: "-----BEGIN RSA PUBLIC KEY-----\n...\n-----END RSA PUBLIC KEY-----"
- This format is RSA-specific
- Suitable for sharing with systems expecting PKCS#1 format
Example:
pemString := publicKey.GetPemPKCS1()
os.WriteFile("public_key.pem", []byte(pemString), 0644)
func (*PublicKey) GetPemPKIX ¶
GetPemPKIX encodes the public key as a PEM-encoded PKIX string.
PKIX (Public-Key Infrastructure X.509) is the algorithm-agnostic public key format defined in X.509. This is the preferred format for modern applications as it can represent public keys from various algorithms.
Returns:
- string: PEM-encoded PKIX public key
- error: Error if encoding fails
Behavior:
- Output format: "-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----"
- Algorithm-agnostic format (includes algorithm identifier)
- Better interoperability with other systems
Example:
pemString, err := publicKey.GetPemPKIX()
if err != nil {
log.Fatal(err)
}
os.WriteFile("public_key_pkix.pem", []byte(pemString), 0644)
func (*PublicKey) GetSsh ¶
GetSsh encodes the public key as an SSH authorized_keys format string.
This method converts the RSA public key to the SSH authorized_keys format, which is used for SSH authentication and other SSH-based systems.
Returns:
- string: SSH authorized_keys format string
- error: Error if encoding fails
Behavior:
- Output format: "ssh-rsa AAAAB3NzaC1yc2EA..." (single line)
- Suitable for ~/.ssh/authorized_keys files
- Compatible with OpenSSH and other SSH implementations
Example:
sshKey, err := publicKey.GetSsh()
if err != nil {
log.Fatal(err)
}
os.WriteFile("id_rsa.pub", []byte(sshKey), 0644)
func (*PublicKey) GetSshPublicKey ¶
GetSshPublicKey converts the public key to an ssh.PublicKey.
This method creates an ssh.PublicKey instance from the RSA public key, which can be used with the golang.org/x/crypto/ssh package for SSH operations.
Returns:
- ssh.PublicKey: The SSH public key instance
- error: Error if conversion fails
Behavior:
- Returns a type that implements ssh.PublicKey interface
- Can be used with ssh package functions
- Preserves all key material
Example:
sshPubKey, err := publicKey.GetSshPublicKey()
if err != nil {
log.Fatal(err)
}
// Use with SSH package
cert := &ssh.Certificate{Key: sshPubKey}
func (*PublicKey) Set ¶
Set assigns an existing rsa.PublicKey to this PublicKey instance.
This method allows setting the public key from an existing Go standard library rsa.PublicKey, useful when loading keys from other sources.
Parameters:
- publicKey: The rsa.PublicKey to assign
Example:
nativeKey := rsa.PublicKey{N: n, E: e}
publicKey := &rsa.PublicKey{}
publicKey.Set(nativeKey)
func (*PublicKey) SetPemPKCS1 ¶
SetPemPKCS1 loads a public key from a PEM-encoded PKCS#1 string.
This method decodes a PEM-encoded PKCS#1 public key and sets it as the current public key. The input should have the "RSA PUBLIC KEY" PEM block type.
Parameters:
- pemPKCS1: PEM-encoded PKCS#1 public key string
Returns:
- error: Error if decoding fails or format is invalid
Behavior:
- Expects "-----BEGIN RSA PUBLIC KEY-----" header
- Validates the RSA public key structure
- Replaces the current key if successful
Example:
pemData, _ := os.ReadFile("public_key.pem")
publicKey := &rsa.PublicKey{}
err := publicKey.SetPemPKCS1(string(pemData))
if err != nil {
log.Fatal(err)
}
func (*PublicKey) SetPemPKIX ¶
SetPemPKIX loads a public key from a PEM-encoded PKIX string.
This method decodes a PEM-encoded PKIX public key and sets it as the current public key. PKIX format is algorithm-agnostic and widely supported.
Parameters:
- pemPKIX: PEM-encoded PKIX public key string
Returns:
- error: Error if decoding fails or key is not RSA
Behavior:
- Expects "-----BEGIN PUBLIC KEY-----" header
- Automatically identifies RSA algorithm from key data
- Type assertion ensures the key is RSA
Example:
pemData, _ := os.ReadFile("public_key_pkix.pem")
publicKey := &rsa.PublicKey{}
err := publicKey.SetPemPKIX(string(pemData))
if err != nil {
log.Fatal(err)
}
func (*PublicKey) SetSsh ¶
SetSsh loads a public key from an SSH authorized_keys format string.
This method parses an SSH authorized_keys format string and sets the RSA public key. The format is commonly found in ~/.ssh/authorized_keys files.
Parameters:
- sshKey: SSH authorized_keys format string (e.g., "ssh-rsa AAAAB3...")
Returns:
- error: Error if parsing fails or key is not RSA
Behavior:
- Accepts single-line SSH format
- Ignores comments and options if present
- Type assertion ensures the key is RSA
Example:
sshData, _ := os.ReadFile("id_rsa.pub")
publicKey := &rsa.PublicKey{}
err := publicKey.SetSsh(string(sshData))
if err != nil {
log.Fatal(err)
}
func (*PublicKey) SetSshPublicKey ¶
SetSshPublicKey loads a public key from an ssh.PublicKey.
This method converts an ssh.PublicKey instance to an RSA public key. The ssh.PublicKey must contain an RSA key, otherwise an error occurs.
Parameters:
- publicKey: The ssh.PublicKey to convert
Returns:
- error: Error if conversion fails or key is not RSA
Behavior:
- Type assertion ensures the key is RSA
- Marshals and unmarshals to ensure proper conversion
- Replaces the current key if successful
Example:
sshPubKey, _ := ssh.ParsePublicKey(sshKeyBytes)
publicKey := &rsa.PublicKey{}
err := publicKey.SetSshPublicKey(sshPubKey)
if err != nil {
log.Fatal(err)
}