Skip to content

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 generator
  • modulusBits - 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 throws InvalidArgument.

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:

ModulusSecurity strength
2048 bits112 bits
3072 bits128 bits
7680 bits192 bits
15360 bits256 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

  1. Always use padding. Use OAEP for encryption and PSS for signatures:

    RSAES_OAEP_SHA256_Encryptor enc(publicKey);
    RSASS<PSS, SHA256>::Signer signer(privateKey);
  2. Use at least a 2048-bit modulus:

    privateKey.Initialize(rng, 3072);
  3. 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");
  4. 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.

ModulusOAEP with SHA-1OAEP with SHA-256
2048-bit214 bytes190 bytes
3072-bit342 bytes318 bytes
4096-bit470 bytes446 bytes

For larger data, use hybrid encryption:

  1. Generate a random AES key
  2. Encrypt the data with AES-GCM
  3. Encrypt the AES key with RSA-OAEP
  4. 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:

  1. Interoperability - Protocols, standards and peers that require RSA
  2. Key transport - Encrypting a symmetric key for the holder of an RSA key
  3. Signatures - Where the verifier does not support Ed25519 or ECDSA

Don’t use RSA for:

  1. Large data - Use symmetric authenticated encryption (AES-GCM) with a transported or agreed key
  2. Forward secrecy - Use an ephemeral key agreement such as X25519
  3. Constrained devices - Keys and signatures are several times larger than their elliptic-curve equivalents

RSA vs Ed25519

RSA-3072Ed25519
Security strength128 bitsAbout 128 bits
Public key384-byte modulus plus exponent32 bytes
Signature384 bytes64 bytes
Signature randomnessPSS uses a random saltNone; 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 key
  • InvalidCiphertext - PK_DecryptorFilter could not decrypt (wrong key or altered ciphertext)
  • BERDecodeErr - Load() or BERDecode() was given a malformed encoding

See Also

References

  1. RFC 8017: PKCS #1: RSA Cryptography Specifications Version 2.2
  2. FIPS 186-5: Digital Signature Standard (DSS)
  3. NIST SP 800-56B Revision 2: Recommendation for Pair-Wise Key Establishment Using Integer Factorization Cryptography
  4. NIST SP 800-57 Part 1 Revision 5: Recommendation for Key Management