TExcelTAD
Home › Applied Cryptography: Ciphers, Hashes, Signatures, PKI & TLS › RSA from Small Numbers to Real Keys

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 pp and qq and compute n=pqn = pq. Multiplying is easy; recovering pp and qq from nn (factoring) is believed to be hard for large nn.
  • Compute φ(n)=(p−1)(q−1)\varphi(n) = (p-1)(q-1) and choose a public exponent ee with gcd⁡(e,φ(n))=1\gcd(e, \varphi(n)) = 1; today almost always e=65537e = 65537.
  • Compute the private exponent d=e−1 mod φ(n)d = e^{-1} \bmod \varphi(n), so that ed≡1(modφ(n))ed \equiv 1 \pmod{\varphi(n)}.
  • Public key (n,e)(n, e), private key dd (plus pp, qq for speed).

Encryption and decryption are modular exponentiation:

c=me mod n,m=cd mod nc = m^e \bmod n, \qquad m = c^d \bmod n

and a signature is the same operation with the roles swapped: s=md mod ns = m^d \bmod n, verified by checking se mod n=ms^e \bmod n = m. Decryption works because med≡m(modn)m^{ed} \equiv m \pmod n by Euler's theorem.

With toy numbers

Real primes have 1,024 bits or more; the example uses p=61p = 61 and q=53q = 53 so every number fits on a line.

python · try it yourself
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: 17×2753=46801=15×3120+117 \times 2753 = 46801 = 15 \times 3120 + 1, so ed≡1(mod3120)ed \equiv 1 \pmod{3120}.

Why textbook RSA is broken

The computation me mod nm^e \bmod n on its own, "textbook RSA", has three fatal properties, all visible above:

  1. 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.
  2. Malleable. (m1m2)e=m1em2e(m_1 m_2)^e = m_1^e m_2^e, so multiplying a ciphertext by 2e2^e 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.
  3. Small messages leak. If me<nm^e < n (a short message with e=3e = 3), no modular reduction happens and the ee-th integer root of cc gives mm. 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 nn. 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.

python · try it yourself
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 gcd⁡(n1,n2)\gcd(n_1, n_2) 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; badkeys checks 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 dd for speed: Wiener's attack recovers dd when it is below about n1/4n^{1/4}.
  • 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 pp; then q1=n1/pq_1 = n_1 / p and q2=n2/pq_2 = n_2 / p, 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?

(c⋅2e)d=cd⋅2ed≡m⋅2(modn)(c \cdot 2^e)^d = c^d \cdot 2^{ed} \equiv m \cdot 2 \pmod n. Textbook RSA is multiplicatively homomorphic; padding destroys that structure.

Test yourself

In RSA, which value is private?

  1. nn
  2. ee
  3. dd
  4. The ciphertext

Why is textbook RSA insecure as an encryption scheme?

  1. It is too slow
  2. It is deterministic and malleable
  3. It cannot decrypt
  4. It needs a nonce

Which RSA modulus size gives about 128-bit security?

  1. 1,024
  2. 2,048
  3. 3,072
  4. 4,096

What caused many embedded devices to share RSA prime factors (2012)?

  1. A bug in the RSA algorithm
  2. Low entropy when generating keys at first boot
  3. Quantum computers
  4. Using e = 65537