RSA from Small Numbers to Real Keys
Symmetric cryptography needs a shared key, and sharing keys with strangers over the Internet is the problem public-key cryptography solves. RSA (Rivest, Shamir, Adleman, 1977) was the first practical public-key system and it is still everywhere: TLS certificates, SSH keys, code signing, smart cards. This lesson builds RSA with numbers small enough to check by hand, shows why "textbook" RSA is not secure, and then generates a real key with the cryptography library. The number theory behind each step is derived in RSA Key Generation.
The idea
- Pick two large primes and and compute . Multiplying is easy; recovering and from (factoring) is believed to be hard for large .
- Compute and choose a public exponent with ; today almost always .
- Compute the private exponent , so that .
- Public key , private key (plus , for speed).
Encryption and decryption are modular exponentiation:
and a signature is the same operation with the roles swapped: , verified by checking . Decryption works because by Euler's theorem.
With toy numbers
Real primes have 1,024 bits or more; the example uses and so every number fits on a line.
from math import gcd
p, q = 61, 53 # toy primes: real RSA uses two secret primes of 1024+ bits each
n = p * q
phi = (p - 1) * (q - 1)
e = 17
assert gcd(e, phi) == 1
d = pow(e, -1, phi) # modular inverse
print(f"n = {n}, phi = {phi}, e = {e}, d = {d}")
m = 65 # a message is a number below n
c = pow(m, e, n)
print(f"encrypt {m} -> {c}, decrypt -> {pow(c, d, n)}")
s = pow(m, d, n)
print(f"sign {m} -> {s}, verify -> {pow(s, e, n) == m}")
# Why textbook RSA is not encryption: it is deterministic and multiplicative.
print("same message, same ciphertext:", pow(m, e, n) == c)
c2 = (c * pow(2, e, n)) % n # attacker multiplies the ciphertext by 2^e
print("tampered ciphertext decrypts to", pow(c2, d, n), "= 2 *", m)
# With a toy n, factoring is instant, which is why real n has 2048+ bits:
f = next(i for i in range(2, n) if n % i == 0)
print("factor n:", f, n // f)n = 3233, phi = 3120, e = 17, d = 2753
encrypt 65 -> 2790, decrypt -> 65
sign 65 -> 588, verify -> True
same message, same ciphertext: True
tampered ciphertext decrypts to 130 = 2 * 65
factor n: 53 61
Check one line by hand: , so .
Why textbook RSA is broken
The computation on its own, "textbook RSA", has three fatal properties, all visible above:
- Deterministic. The same message always gives the same ciphertext. An attacker who suspects the message is "yes" or "no" encrypts both with the public key and compares.
- Malleable. , so multiplying a ciphertext by doubles the hidden message (65 became 130) without the key. The same property lets an attacker blind a message, get it signed or decrypted, and unblind the result.
- Small messages leak. If (a short message with ), no modular reduction happens and the -th integer root of gives . A signature on a hash without padding allows forgeries of related values.
The fix is padding with randomness and structure: OAEP for encryption and PSS for signatures, the subject of the next lesson. The attacks are worked through in Textbook RSA Attacks.
Key size
The security of RSA rests on factoring . The best known classical algorithm, the general number field sieve, is sub-exponential, which is why RSA keys are so much longer than symmetric keys for the same strength:
| Security level | Symmetric | RSA modulus | Elliptic curve |
|---|---|---|---|
| 80 bits (obsolete) | 2TDEA | 1,024 | 160 |
| 112 bits | 3TDEA | 2,048 | 224 |
| 128 bits | AES-128 | 3,072 | 256 |
| 192 bits | AES-192 | 7,680 | 384 |
| 256 bits | AES-256 | 15,360 | 512 |
(NIST SP 800-57 Part 1.) The largest RSA modulus publicly factored is RSA-250, 829 bits, in 2020. RSA-2048 is the current minimum for new keys and is expected to be acceptable until about 2030; 3,072 bits for anything that must stay secure longer. A large quantum computer running Shor's algorithm would factor any of these, which is the reason for the post-quantum migration.
A real key
cryptography generates a key in one call. Key generation is random, so the example prints sizes, not values.
from math import lcm
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization
key = rsa.generate_private_key(public_exponent=65537, key_size=3072) # a new key on every run
nums = key.private_numbers()
pub = key.public_key().public_numbers()
print("modulus bits:", pub.n.bit_length(), " e =", pub.e)
print("p bits:", nums.p.bit_length(), " q bits:", nums.q.bit_length(), " p*q == n:", nums.p * nums.q == pub.n)
print("e*d mod lcm(p-1, q-1) == 1:", pub.e * nums.d % lcm(nums.p - 1, nums.q - 1) == 1)
pem = key.public_key().public_bytes(serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo)
print(pem.decode().splitlines()[0], "...")modulus bits: 3072 e = 65537
p bits: 1536 q bits: 1536 p*q == n: True
e*d mod lcm(p-1, q-1) == 1: True
-----BEGIN PUBLIC KEY----- ...
Real-world RSA failures
- Weak randomness at key generation: in 2012 Heninger, Durumeric, Wustrow and Halderman (and independently Lenstra and colleagues) found that tens of thousands of TLS and SSH keys on embedded devices shared a prime factor with another key, because the devices generated keys right after boot with little entropy. Computing for pairs of keys factored them instantly.
- Flawed prime generation: the 2017 ROCA flaw (CVE-2017-15361) in an Infineon library produced primes with a structure that made 2,048-bit keys factorable for tens of thousands of dollars of computation; it affected smart cards, TPMs and the Estonian ID card.
- Debian OpenSSL, 2008 (CVE-2008-0166): a patch removed most of the entropy from OpenSSL's random generator on Debian and Ubuntu, so only 32,768 possible keys per type, size and architecture existed for almost two years (September 2006 to May 2008).
How weak RSA is detected
- Key size:
openssl x509 -noout -text | grep 'Public-Key',ssh-keygen -lf key.pub; flag anything below 2,048 bits. - Known-bad keys: blocklists of Debian weak keys and ROCA fingerprints (the ROCA authors published a detector;
badkeyschecks many known flaws at once). - Shared factors across your own key inventory: batch GCD over all moduli.
- Textbook use in code: raw
pow(m, e, n),RSA/ECB/NoPadding,padding=None, PKCS#1 v1.5 encryption in new code.
How it is fixed
- Generate keys with a maintained library on a system with a properly seeded CSPRNG, at 3,072 bits for long-term use (or move to elliptic curves).
- Always use OAEP for encryption and PSS (or at least PKCS#1 v1.5 signatures, which remain unbroken) for signatures; never raw RSA.
- Replace keys found on blocklists and rotate keys made by affected devices.
Pitfalls
- "RSA-2048 is 2,048-bit security": it is about 112 bits.
- Choosing a small private exponent for speed: Wiener's attack recovers when it is below about .
- Encrypting large data with RSA directly: RSA encrypts a symmetric key (or, better, use a key exchange), and the data goes through an AEAD.
Practice
1. With the toy key $(n, e) = (3233, 17)$, encrypt $m = 42$ and decrypt it with $d = 2753$.
pow(42, 17, 3233) gives the ciphertext, and pow(c, 2753, 3233) returns 42. Run it in the example by changing m.
2. Two IoT devices have RSA moduli $n_1$ and $n_2$ with $\gcd(n_1, n_2) > 1$. What follows?
The gcd is a shared prime ; then and , and both private keys can be computed. Both devices must get new keys generated with proper entropy.
3. Why does multiplying the toy ciphertext by $2^e \bmod n$ double the plaintext?
. Textbook RSA is multiplicatively homomorphic; padding destroys that structure.
Test yourself
In RSA, which value is private?
- The ciphertext
Why is textbook RSA insecure as an encryption scheme?
- It is too slow
- It is deterministic and malleable
- It cannot decrypt
- It needs a nonce
Which RSA modulus size gives about 128-bit security?
- 1,024
- 2,048
- 3,072
- 4,096
What caused many embedded devices to share RSA prime factors (2012)?
- A bug in the RSA algorithm
- Low entropy when generating keys at first boot
- Quantum computers
- Using e = 65537