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.

Advanced 4 min readLesson 7 of 12 Interview Q&A

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: a mod na \bmod n is the remainder after dividing by n. Arithmetic "wraps around" like a clock (Number theory).
  • Modular exponentiation me mod nm^e \bmod n is fast even for 2048-bit numbers using square-and-multiply — O(log e) multiplications.
  • Euler's totient φ(n)\varphi(n) counts integers in [1,n][1, n] coprime to n. For n = pq with primes p, q: φ(n)=(p−1)(q−1)\varphi(n) = (p-1)(q-1).
  • Euler's theorem: if gcd(m, n) = 1, then mφ(n)≡1(modn)m^{\varphi(n)} \equiv 1 \pmod n.
  • Modular inverse: d with e⋅d≡1(modφ(n))e \cdot d \equiv 1 \pmod{\varphi(n)}, found with the extended Euclidean algorithm.

Key generation

  1. Pick two large random primes p and q (each 1024+ bits for RSA-2048).
  2. Compute the modulus n=p⋅qn = p \cdot q.
  3. Compute φ(n)=(p−1)(q−1)\varphi(n) = (p-1)(q-1).
  4. Choose the public exponent e, coprime to φ(n) — almost always 65537.
  5. Compute the private exponent d=e−1 mod φ(n)d = e^{-1} \bmod \varphi(n).
  6. Public key: (n, e). Private key: d (and p, q for speed). Destroy φ(n) or keep it secret.

Encryption and decryption

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

Why it works: cd=medc^d = m^{ed}, and since ed=1+kφ(n)ed = 1 + k\varphi(n), we get med=m⋅(mφ(n))k≡m⋅1k=m(modn)m^{ed} = m \cdot (m^{\varphi(n)})^k \equiv m \cdot 1^k = m \pmod n by Euler's theorem.

Signatures run it the other way: s=hd mod ns = h^d \bmod n (using the private key on a hash of the message); anyone checks se mod n=hs^e \bmod n = h.

A worked example (tiny numbers)

Python
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 key

Real 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 c=me mod nc = m^e \bmod n ("textbook RSA") has fatal flaws:

FlawProblem
DeterministicThe same message always encrypts to the same ciphertext — an attacker can guess "yes"/"no" and compare
Malleablec⋅2ec \cdot 2^e decrypts to 2m2m: ciphertexts can be manipulated meaningfully
Small messagesIf me<nm^e < n (e.g. e = 3, short m), just take the integer e-th root — no modulus involved
Signature forgeryMultiplying signatures gives a valid signature of the product of messages

Fix: randomised padding that adds structure and randomness before exponentiation:

UseSchemeAvoid
EncryptionRSA-OAEPPKCS#1 v1.5 encryption padding — vulnerable to Bleichenbacher's padding oracle attack (1998), which keeps resurfacing (ROBOT, 2017)
SignaturesRSA-PSS (or PKCS#1 v1.5 signatures, still considered OK)Textbook signatures
Python
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 forged

Performance

  • 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 sizeStatus
512, 768, 1024 bitsBroken or deprecated
2048 bitsMinimum today (~112-bit security)
3072 bits~128-bit security; recommended for new long-lived keys
4096 bitsExtra 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.

Key takeaways
  • 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.
Interview questions
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.