RSA
How RSA works — modular arithmetic, Euler's totient, key generation, encryption and decryption, a worked example with small numbers, why it's secure (factoring), why textbook RSA is insecure, OAEP and PSS padding, performance tricks, key sizes, and RSA's decline.
RSA (Rivest, Shamir, Adleman, 1977) was the first practical public-key cryptosystem and remains widely deployed for signatures and certificates. Its maths fits on one page — but using it safely requires much more than the maths.
The maths you need
- Modular arithmetic: is the remainder after dividing by n. Arithmetic "wraps around" like a clock (Number theory).
- Modular exponentiation is fast even for 2048-bit numbers using square-and-multiply — O(log e) multiplications.
- Euler's totient counts integers in coprime to n. For n = pq with primes p, q: .
- Euler's theorem: if gcd(m, n) = 1, then .
- Modular inverse: d with , found with the extended Euclidean algorithm.
Key generation
- Pick two large random primes p and q (each 1024+ bits for RSA-2048).
- Compute the modulus .
- Compute .
- Choose the public exponent e, coprime to φ(n) — almost always 65537.
- Compute the private exponent .
- Public key: (n, e). Private key: d (and p, q for speed). Destroy φ(n) or keep it secret.
Encryption and decryption
Why it works: , and since , we get by Euler's theorem.
Signatures run it the other way: (using the private key on a hash of the message); anyone checks .
A worked example (tiny numbers)
p, q = 61, 53
n = p * q # 3233
phi = (p - 1) * (q - 1) # 3120
e = 17 # coprime with 3120
d = pow(e, -1, phi) # 2753, since 17 × 2753 = 46801 = 15 × 3120 + 1
m = 65 # message as a number < n
c = pow(m, e, n) # 2790 — encryption
assert pow(c, d, n) == m # 65 — decryption
h = 123 # "hash" of a message
s = pow(h, d, n) # sign with the private key
assert pow(s, e, n) == h # verify with the public keyReal keys use n of 2048–4096 bits (617–1233 decimal digits).
Why it's secure
Knowing (n, e), computing d requires φ(n), which requires the factors p and q. Factoring a 2048-bit n is far beyond the best known classical algorithm (the general number field sieve). The record publicly factored RSA modulus is 829 bits (RSA-250, 2020, ~2,700 core-years).
Shor's algorithm on a large quantum computer would factor n efficiently — RSA is not post-quantum secure (Public-key cryptography).
Textbook RSA is insecure
The bare formula ("textbook RSA") has fatal flaws:
| Flaw | Problem |
|---|---|
| Deterministic | The same message always encrypts to the same ciphertext — an attacker can guess "yes"/"no" and compare |
| Malleable | decrypts to : ciphertexts can be manipulated meaningfully |
| Small messages | If (e.g. e = 3, short m), just take the integer e-th root — no modulus involved |
| Signature forgery | Multiplying signatures gives a valid signature of the product of messages |
Fix: randomised padding that adds structure and randomness before exponentiation:
| Use | Scheme | Avoid |
|---|---|---|
| Encryption | RSA-OAEP | PKCS#1 v1.5 encryption padding — vulnerable to Bleichenbacher's padding oracle attack (1998), which keeps resurfacing (ROBOT, 2017) |
| Signatures | RSA-PSS (or PKCS#1 v1.5 signatures, still considered OK) | Textbook signatures |
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import hashes
private_key = rsa.generate_private_key(public_exponent=65537, key_size=3072)
public_key = private_key.public_key()
ct = public_key.encrypt(b"session key bytes",
padding.OAEP(mgf=padding.MGF1(hashes.SHA256()), algorithm=hashes.SHA256(), label=None))
pt = private_key.decrypt(ct, padding.OAEP(mgf=padding.MGF1(hashes.SHA256()), algorithm=hashes.SHA256(), label=None))
sig = private_key.sign(b"release-v1.4.2.tar.gz digest",
padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH),
hashes.SHA256())
public_key.verify(sig, b"release-v1.4.2.tar.gz digest",
padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH),
hashes.SHA256()) # raises InvalidSignature if forgedPerformance
- Public operations are fast: e = 65537 (binary 10000000000000001) needs only 17 multiplications.
- Private operations are slow: d is as large as n. The Chinese Remainder Theorem (CRT) optimisation computes modulo p and q separately (half-size numbers), about 4× faster — which is why private keys store p, q and extra CRT values.
- Key generation is slow (finding large primes with probabilistic Miller–Rabin tests).
- RSA encrypts at most a few hundred bytes — only used to protect symmetric keys or hashes.
Implementation pitfalls
- Bad randomness: keys generated with too little entropy share prime factors; computing the GCD of millions of public keys from the internet has recovered private keys for tens of thousands of devices.
- Timing and power side channels in private-key operations → use constant-time implementations with blinding.
- Fault attacks on CRT: one faulty computation can reveal p (the Bellcore attack) → verify signatures before releasing them.
- Small or shared exponents, reused moduli, keys under 2048 bits.
Key sizes and status
| Key size | Status |
|---|---|
| 512, 768, 1024 bits | Broken or deprecated |
| 2048 bits | Minimum today (~112-bit security) |
| 3072 bits | ~128-bit security; recommended for new long-lived keys |
| 4096 bits | Extra margin, slower |
RSA is in decline for new designs: TLS 1.3 removed RSA key transport (no forward secrecy) and uses ephemeral (EC)DH for key exchange; elliptic-curve signatures (Ed25519, ECDSA) are smaller and faster. RSA remains common for certificate signatures, code signing and legacy systems.
- RSA: n = pq, public (n, e), private d = e⁻¹ mod φ(n); encrypt mᵉ mod n, decrypt cᵈ mod n.
- Security rests on the difficulty of factoring n; quantum computers would break it.
- Textbook RSA is deterministic and malleable — always use OAEP for encryption and PSS for signatures.
- Public operations are fast (e = 65537); private operations use CRT for speed.
- Bad randomness, side channels and fault attacks break implementations; use vetted libraries.
- Use ≥ 2048-bit keys (3072 for new); prefer ECDH for key exchange and Ed25519/ECDSA for signatures in new designs.
QWhy is textbook RSA insecure and how is it fixed?hard
Textbook RSA is deterministic, so identical plaintexts give identical ciphertexts and guesses can be confirmed; it's malleable, since multiplying a ciphertext by 2ᵉ doubles the plaintext; and small messages with small exponents can be recovered by taking integer roots. Fixes add randomised, structured padding before exponentiation: OAEP for encryption and PSS for signatures. Implementations must also avoid padding oracles, timing side channels and fault attacks.