Skip to content
KALANBLON
Show contents

Chapter 2 of 6 · 20 min

RSA encryption

By the end of this chapter, you'll be able to

  • Generate an RSA key pair from two large primes
  • Encrypt and decrypt a message with the public key and the private key
  • Explain why RSA's security relies on the difficulty of factoring n
  • Recognise the weakness of RSA without padding and name OAEP

RSA keys

The private key. Public key: (n, e). Private key: (n, d).

Step 5 of 5
Text description of the animation
  1. Two primes drawn at random, kept secret.
  2. Their product is published. Finding p and q from n means factoring: out of reach at this size.
  3. This number can only be computed easily if you know p and q.
  4. Almost everyone uses this value, coprime with φ(n).
  5. The private key. Public key: (n, e). Private key: (n, d).

To encrypt a number m (smaller than n), we compute c = m^e mod n. To decrypt, m = c^d mod n. It works because e × d = 1 mod φ(n), and a theorem of Euler then guarantees that (m^e)^d = m mod n. Let's start with tiny numbers:

p, q = 61, 53
n = p * q                        # 3233
phi = (p - 1) * (q - 1)          # 3120
e = 17
d = pow(e, -1, phi)              # 2753

m = 65                           # the message, a number smaller than n
c = pow(m, e, n)
print(f"public key (n={n}, e={e}), private key d={d}")
print("encrypted:", c)
print("decrypted:", pow(c, d, n))
public key (n=3233, e=17), private key d=2753
encrypted: 2790
decrypted: 65

With real numbers, we generate p and q with the previous chapter's Miller-Rabin test, and turn the text into a large integer with int.from_bytes.

import random

def miller_rabin(n, rng, k=40):
    if n % 2 == 0:
        return n == 2
    s, d = 0, n - 1
    while d % 2 == 0:
        s, d = s + 1, d // 2
    for _ in range(k):
        x = pow(rng.randrange(2, n - 1), d, n)
        if x in (1, n - 1):
            continue
        for _ in range(s - 1):
            x = pow(x, 2, n)
            if x == n - 1:
                break
        else:
            return False
    return True

def prime(bits, rng):
    while True:
        n = rng.getrandbits(bits) | (1 << (bits - 1)) | 1
        if miller_rabin(n, rng):
            return n

rng = random.Random(2026)        # for a reproducible example; for real: random.SystemRandom()
p, q = prime(512, rng), prime(512, rng)
n, e = p * q, 65537
d = pow(e, -1, (p - 1) * (q - 1))

message = "Meet at Mei's place at 7 pm".encode()
m = int.from_bytes(message, "big")
c = pow(m, e, n)
back = pow(c, d, n).to_bytes(len(message), "big").decode()

print("size of n :", n.bit_length(), "bits")
print("encrypted :", str(c)[:30], "…")
print("decrypted :", back)
size of n : 1023 bits
encrypted : 559175413414239407000267675069 …
decrypted : Meet at Mei's place at 7 pm

Why it is safe: factorisation

To compute d, you need φ(n) = (p − 1)(q − 1), and therefore p and q. But finding two large prime factors from their product is factorisation, and no known method does it quickly on a classical computer. The public record, RSA-250 (829 bits), was factored in 2020 with the equivalent of about 2,700 years of computation on one processor core. Today at least 3,072 bits are recommended for long-term use (2,048 at the very least).

For small numbers, on the other hand, factorisation is immediate: that is what the exercise is about.

Mini-lab: RSA in miniaturePython 3.13

Output

Click “Run”: Python will load in your browser (about 10 MB the first time).

Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Your turn

Worked exercise

Worked exercise: breaking a small RSA key

A developer in a hurry generated an RSA key with small primes. Here is the public key and an intercepted ciphertext:

n = 1022117
e = 65537
c = 801181

Find p and q by trying divisors, compute d, then decrypt c. The message is a 6-digit code.

Hint 1
Try the odd divisors k from 3 up to √n: the first k such that n % k == 0 gives p = k and q = n // k.
Hint 2
Then: phi = (p - 1) * (q - 1), d = pow(e, -1, phi) and m = pow(c, d, n).
Show the solution and common mistakes
n, e, c = 1022117, 65537, 801181

p = next(k for k in range(3, int(n ** 0.5) + 1, 2) if n % k == 0)
q = n // p
d = pow(e, -1, (p - 1) * (q - 1))
print(f"p = {p}, q = {q}, d = {d}")
print("code:", pow(c, d, n))
p = 1009, q = 1013, d = 832193
code: 482913

With n around one million, a few hundred divisors are enough. Each extra digit in n multiplies this work; with 925 digits (3,072 bits), even the best known methods (the number field sieve) are out of reach.

Common mistakes:

  • Computing d as the inverse of e modulo n instead of φ(n): decryption gives nonsense.
  • Looking for divisors up to n instead of √n: if n = p × q, one of them is necessarily less than or equal to √n.
  • Forgetting that m must be smaller than n: a larger message is reduced modulo n and lost.

Summary

  1. 1RSA: n = p × q public, e public, d = inverse of e modulo (p − 1)(q − 1) private.
  2. 2Encrypt with c = m^e mod n and decrypt with m = c^d mod n.
  3. 3Security relies on the difficulty of factoring n: at least 2,048 bits, 3,072 recommended.
  4. 4Textbook RSA is deterministic and malleable: always use OAEP padding (or PSS for signing).

Your progress is saved on this device. Create a free account to keep your progress on all your devices.