RSA
Header: #include <cryptopp/rsa.h> | Namespace: CryptoPP
Since: Crypto++ 1.0
RSA is a public-key cryptosystem that can be used for both encryption and digital signatures. It remains widely deployed. New designs that are free to choose usually prefer Ed25519 for signatures and X25519 or ECDH for key exchange, which have smaller keys and faster private-key operations.
Quick Example
#include <cryptopp/rsa.h>
#include <cryptopp/oaep.h>
#include <cryptopp/osrng.h>
#include <cryptopp/filters.h>
#include <iostream>
int main() {
using namespace CryptoPP;
AutoSeededRandomPool rng;
// Generate 2048-bit RSA key pair
RSA::PrivateKey privateKey;
privateKey.Initialize(rng, 2048);
RSA::PublicKey publicKey(privateKey);
// Encrypt with OAEP padding (SHA-256)
RSAES_OAEP_SHA256_Encryptor encryptor(publicKey);
std::string message = "Secret message";
std::string ciphertext;
StringSource(message, true,
new PK_EncryptorFilter(rng, encryptor,
new StringSink(ciphertext)
)
);
// Decrypt
RSAES_OAEP_SHA256_Decryptor decryptor(privateKey);
std::string recovered;
StringSource(ciphertext, true,
new PK_DecryptorFilter(rng, decryptor,
new StringSink(recovered)
)
);
std::cout << "Decrypted: " << recovered << std::endl;
return recovered == message ? 0 : 1;
}Usage Guidelines
Use RSA for:
- Interoperability with systems and standards that require it
- Encrypting a short symmetric key for a recipient who has an RSA key
- Signatures where the verifier only supports RSA
Guidelines:
- Always use a padding scheme: OAEP for encryption, PSS for signatures. PKCS #1 v1.5 is for compatibility with existing systems.
- Use a modulus of at least 2048 bits; 3072 bits corresponds to a 128-bit security strength in NIST SP 800-57 Part 1.
- RSA encrypts only short messages. Encrypt data with an authenticated cipher such as AES-GCM and use RSA-OAEP for the data key.
- Key generation is much slower than for elliptic-curve keys and grows quickly with the modulus size.
Class: RSA::PrivateKey
RSA private key for decryption and signing.
Constructors
RSA::PrivateKey();RSA::PrivateKey is a typedef for InvertibleRSAFunction. It has only a default constructor, which creates an empty key. Generate or load a key with Initialize(), Load() or BERDecode().
Methods
Initialize()
// Generate a new key pair
void Initialize(RandomNumberGenerator& rng, unsigned int modulusBits,
const Integer& e = 17);
// Load an existing key
void Initialize(const Integer& n, const Integer& e, const Integer& d);
void Initialize(const Integer& n, const Integer& e, const Integer& d,
const Integer& p, const Integer& q,
const Integer& dp, const Integer& dq, const Integer& u);The first overload generates a new key pair. The others load existing key values; the three-value form factors n using d to recover the remaining values and throws InvalidArgument if they are not a valid RSA private key.
Parameters:
rng- Random number generatormodulusBits- Modulus size in bits (2048 or more)e- Public exponent. The default is 17. Pass 65537 where a protocol or policy requires it. An even value is raised to the next odd number, and a value below 3 throwsInvalidArgument.
Example:
AutoSeededRandomPool rng;
RSA::PrivateKey privateKey;
// 3072-bit key with the default public exponent (17)
privateKey.Initialize(rng, 3072);
// 3072-bit key with public exponent 65537
RSA::PrivateKey privateKey2;
privateKey2.Initialize(rng, 3072, Integer(65537));Save() / Load()
void Save(BufferedTransformation& bt) const;
void Load(BufferedTransformation& bt);Save() writes the key as a DER-encoded PKCS #8 PrivateKeyInfo and Load() reads one. The encoding is not encrypted.
DEREncodePrivateKey() and BERDecodePrivateKey() handle only the inner PKCS #1 RSAPrivateKey structure, without the PKCS #8 wrapper.
Example:
// Save private key (PKCS #8, unencrypted)
FileSink out("private.key");
privateKey.Save(out);
out.MessageEnd();
// Load private key
FileSource in("private.key", true);
RSA::PrivateKey loadedKey;
loadedKey.Load(in);Class: RSA::PublicKey
RSA public key for encryption and verification.
Constructors
RSA::PublicKey();RSA::PublicKey is a typedef for RSAFunction. The default constructor creates an empty key.
From a Private Key
InvertibleRSAFunction derives from RSAFunction, so a public key can be copy-constructed from a private key. The copy holds the modulus and public exponent only.
Example:
RSA::PrivateKey privateKey;
privateKey.Initialize(rng, 2048);
RSA::PublicKey publicKey(privateKey);Methods
Initialize()
void Initialize(const Integer& n, const Integer& e);Load a public key from its modulus and public exponent.
Save() / Load()
void Save(BufferedTransformation& bt) const;
void Load(BufferedTransformation& bt);Save() writes the key as a DER-encoded X.509 SubjectPublicKeyInfo and Load() reads one.
DEREncodePublicKey() and BERDecodePublicKey() handle only the inner PKCS #1 RSAPublicKey structure.
RSA-OAEP Encryption
RSA with Optimal Asymmetric Encryption Padding (RSAES-OAEP in RFC 8017).
RSAES_OAEP_SHA256_Encryptor / RSAES_OAEP_SHA256_Decryptor
RSAES_OAEP_SHA256_Encryptor enc(publicKey);
RSAES_OAEP_SHA256_Decryptor dec(privateKey);RSA-OAEP with SHA-256 for both the label hash and MGF1. These are typedefs for RSAES<OAEP<SHA256> >::Encryptor and Decryptor. Other hashes use the template form, for example RSAES<OAEP<SHA384> >::Encryptor.
RSAES_OAEP_SHA_Encryptor / RSAES_OAEP_SHA_Decryptor
RSAES_OAEP_SHA_Encryptor enc(publicKey);
RSAES_OAEP_SHA_Decryptor dec(privateKey);RSA-OAEP with SHA-1, for compatibility with systems that use it.
Both sides must use the same hash. A ciphertext that fails to decrypt makes PK_DecryptorFilter throw InvalidCiphertext; calling Decrypt() directly returns a DecodingResult whose isValidCoding is false.
RSA-PSS Signatures
RSA with the Probabilistic Signature Scheme (RSASSA-PSS in RFC 8017).
Using RSA-PSS
RSASS<PSS, SHA256>::Signer signer(privateKey);
RSASS<PSS, SHA256>::Verifier verifier(publicKey);Sign and verify data using RSA-PSS with SHA-256. PSS has no convenience typedefs; use the template form. pssr.h declares PSS.
For compatibility with systems that require PKCS #1 v1.5 signatures, use RSASS<PKCS1v15, SHA256>::Signer and Verifier.
Complete Example: Digital Signatures
#include <cryptopp/rsa.h>
#include <cryptopp/pssr.h>
#include <cryptopp/osrng.h>
#include <cryptopp/filters.h>
#include <iostream>
using namespace CryptoPP;
int main() {
AutoSeededRandomPool rng;
// Generate 3072-bit key
RSA::PrivateKey privateKey;
privateKey.Initialize(rng, 3072);
RSA::PublicKey publicKey(privateKey);
// Create signer
RSASS<PSS, SHA256>::Signer signer(privateKey);
// Sign message
std::string message = "Important document";
std::string signature;
StringSource(message, true,
new SignerFilter(rng, signer,
new StringSink(signature)
)
);
std::cout << "Signature size: " << signature.size()
<< " bytes" << std::endl;
// Create verifier
RSASS<PSS, SHA256>::Verifier verifier(publicKey);
// Verify signature
bool valid = verifier.VerifyMessage(
(const byte*)message.data(), message.size(),
(const byte*)signature.data(), signature.size());
std::cout << "Signature valid: " << (valid ? "YES" : "NO") << std::endl;
return valid ? 0 : 1;
}Performance
Private-key operations (decryption and signing) are much slower than public-key operations (encryption and verification), and the cost of both rises with the modulus size. Key generation is slower again and varies from run to run because it searches for primes. cryptest b measures RSA on your own hardware.
Security
Key Sizes
NIST SP 800-57 Part 1 gives these comparable security strengths for RSA moduli:
| Modulus | Security strength |
|---|---|
| 2048 bits | 112 bits |
| 3072 bits | 128 bits |
| 7680 bits | 192 bits |
| 15360 bits | 256 bits |
SP 800-57 does not list a 4096-bit modulus; it falls between the 3072-bit and 7680-bit rows. A 1024-bit modulus is rated at no more than 80 bits and should not be used for new protection.
RSA at any size would be broken by a sufficiently large quantum computer running Shor’s algorithm. See Post-Quantum Cryptography.
Security Best Practices
Always use padding. Use OAEP for encryption and PSS for signatures:
RSAES_OAEP_SHA256_Encryptor enc(publicKey); RSASS<PSS, SHA256>::Signer signer(privateKey);Use at least a 2048-bit modulus:
privateKey.Initialize(rng, 3072);Validate keys from outside sources.
Validate()at level 3 runs the full checks on a loaded key:if (!loadedKey.Validate(rng, 3)) throw std::runtime_error("RSA key failed validation");Protect private keys.
Save()writes the private key unencrypted. Encrypt the encoding with an authenticated cipher, or keep it in a key store, before it reaches disk.
Maximum Message Sizes
RSA-OAEP encrypts at most k - 2 * hLen - 2 bytes, where k is the modulus length in bytes and hLen the hash output length (RFC 8017 section 7.1.1). FixedMaxPlaintextLength() returns the limit for an encryptor.
| Modulus | OAEP with SHA-1 | OAEP with SHA-256 |
|---|---|---|
| 2048-bit | 214 bytes | 190 bytes |
| 3072-bit | 342 bytes | 318 bytes |
| 4096-bit | 470 bytes | 446 bytes |
For larger data, use hybrid encryption:
- Generate a random AES key
- Encrypt the data with AES-GCM
- Encrypt the AES key with RSA-OAEP
- Send the encrypted AES key with the encrypted data
Thread Safety
Not thread-safe. Use separate key, encryptor, decryptor, signer and verifier objects in each thread.
When to Use RSA
Use RSA for:
- Interoperability - Protocols, standards and peers that require RSA
- Key transport - Encrypting a symmetric key for the holder of an RSA key
- Signatures - Where the verifier does not support Ed25519 or ECDSA
Don’t use RSA for:
- Large data - Use symmetric authenticated encryption (AES-GCM) with a transported or agreed key
- Forward secrecy - Use an ephemeral key agreement such as X25519
- Constrained devices - Keys and signatures are several times larger than their elliptic-curve equivalents
RSA vs Ed25519
| RSA-3072 | Ed25519 | |
|---|---|---|
| Security strength | 128 bits | About 128 bits |
| Public key | 384-byte modulus plus exponent | 32 bytes |
| Signature | 384 bytes | 64 bytes |
| Signature randomness | PSS uses a random salt | None; signatures are deterministic |
Choose RSA when the other party or a standard requires it; otherwise Ed25519 gives smaller keys and signatures at a comparable strength.
Exceptions
InvalidArgument-Initialize()was given a modulus size that is too small, a public exponent below 3, or values that are not a valid RSA private keyInvalidCiphertext-PK_DecryptorFiltercould not decrypt (wrong key or altered ciphertext)BERDecodeErr-Load()orBERDecode()was given a malformed encoding
See Also
- Ed25519 - Modern digital signatures (recommended)
- X25519 - Modern key exchange (recommended)
- AES-GCM - For encrypting large data
- Public-Key Cryptography - Overview