A simple and secure Go library for RSA encryption, decryption, signing, and verification. This library supports OAEP, PSS, and PKCS#1 v1.5 schemes and enforces NIST standards for key sizes.
- Key Generation: Generates RSA key pairs with a minimum size of 2048 bits (NIST standard).
- Encryption/Decryption:
- RSA-OAEP (with SHA-256) - Recommended
- RSA-PKCS#1 v1.5 - Deprecated (NIST recommends OAEP)
- Signing/Verification:
- RSA-PSS (with SHA-256) - Recommended
- RSA-PKCS#1 v1.5 (with SHA-256)
- Key Management: Import and export keys in PEM format.
This library enforces NIST recommendations:
- Minimum Key Size: 2048 bits. Key generation will fail for smaller sizes.
- Hash Function: SHA-256 is used for OAEP and PSS.
- Encryption: RSA-OAEP is the recommended scheme. PKCS#1 v1.5 is marked as deprecated.
go get github.com/fawwazid/go-rsaimport (
"fmt"
"log"
gorsa "github.com/fawwazid/go-rsa"
)// Generate a new RSA key pair (minimum 2048 bits)
priv, pub, err := gorsa.GenerateKeys(2048)
if err != nil {
log.Fatalf("Failed to generate keys: %v", err)
}Recommended for new applications.
msg := []byte("Secret Message")
label := []byte("optional-label")
// Encrypt
ciphertext, err := gorsa.EncryptOAEP(pub, msg, label)
if err != nil {
log.Fatal(err)
}
// Decrypt
plaintext, err := gorsa.DecryptOAEP(priv, ciphertext, label)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Decrypted: %s\n", plaintext)Supported for legacy compatibility only. NIST recommends using OAEP.
msg := []byte("Secret Message")
// Encrypt
ciphertext, err := gorsa.EncryptPKCS1v15(pub, msg)
if err != nil {
log.Fatal(err)
}
// Decrypt
plaintext, err := gorsa.DecryptPKCS1v15(priv, ciphertext)
if err != nil {
log.Fatal(err)
}Recommended for new applications.
// Sign
signature, err := gorsa.SignPSS(priv, msg)
if err != nil {
log.Fatal(err)
}
// Verify
err = gorsa.VerifyPSS(pub, msg, signature)
if err != nil {
log.Fatal("Verification failed")
}
fmt.Println("Signature verified!")Supported for legacy compatibility.
msg := []byte("Secret Message")
// Sign
signature, err := gorsa.SignPKCS1v15(priv, msg)
if err != nil {
log.Fatal(err)
}
// Verify
err = gorsa.VerifyPKCS1v15(pub, msg, signature)
if err != nil {
log.Fatal("Verification failed")
}// Export to PEM
privPEM, err := gorsa.PrivateKeyToPEM(priv)
if err != nil {
log.Fatal(err)
}
pubPEM, err := gorsa.PublicKeyToPEM(pub)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Private Key:\n%s\n", privPEM)
fmt.Printf("Public Key:\n%s\n", pubPEM)
// Import from PEM
parsedPriv, err := gorsa.ParsePrivateKeyFromPEM(privPEM)
if err != nil {
log.Fatal(err)
}
parsedPub, err := gorsa.ParsePublicKeyFromPEM(pubPEM)
if err != nil {
log.Fatal(err)
}This project is licensed under the MIT License - see the LICENSE file for details.