TExcelTAD

RSA: Key Generation and Cost

RSA puts the three previous lessons together: Miller-Rabin finds the primes, extended Euclid computes the private exponent, and modular exponentiation encrypts, decrypts and signs. Why it is correct (Euler's theorem) and why it must never be used without padding are explained in the cryptography part of Number Theory & Cryptography (RSA Key Generation, Textbook RSA Attacks). This lesson asks the algorithmic questions: how long each step takes for a β\beta-bit modulus, how many random candidates key generation must try, and where the asymmetry between easy and hard lies.

The scheme in five lines

text
RSA-KEYGEN(beta)                       // a beta-bit modulus
1  p, q = two random primes of beta/2 bits each, p != q
2  n = p * q;  phi = (p - 1)(q - 1)
3  e = 65537                            // a fixed small odd exponent; need gcd(e, phi) = 1
4  d = the inverse of e modulo phi      // extended Euclid
5  return public key (e, n), secret key (d, n)

ENCRYPT(m) = m^e mod n          DECRYPT(c) = c^d mod n       // 0 <= m < n

Correctness: ed≡1(modφ(n))ed \equiv 1 \pmod{\varphi(n)}, so med≡m(modn)m^{ed} \equiv m \pmod n for every mm, by Euler's theorem and the Chinese remainder theorem.

Finding the primes

By the prime number theorem (The Prime Number Theorem), about one number in ln⁡N\ln N near NN is prime. A random odd kk-bit number is prime with probability about 2/(kln⁡2)2/(k \ln 2), so the expected number of odd candidates is about (kln⁡2)/2(k \ln 2)/2: roughly 355 for k=1024k = 1024. Most candidates are rejected cheaply, by trial division by small primes or by the first Miller-Rabin round; only the final prime needs all the rounds.

The program generates toy keys with 64-bit and 256-bit primes from a fixed seed, counting candidates and Miller-Rabin rounds.

python · try it yourself
import random

SMALL = [3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

def is_probable_prime(n, rounds, rng, stats):
    if any(n % p == 0 for p in SMALL):
        return n in SMALL
    t, u = 0, n - 1
    while u % 2 == 0:
        t, u = t + 1, u // 2
    for _ in range(rounds):
        stats["mr rounds"] += 1
        a = rng.randrange(2, n - 1)
        x = pow(a, u, n)
        if x in (1, n - 1):
            continue
        for _ in range(t - 1):
            x = x * x % n
            if x == n - 1:
                break
        else:
            return False
    return True

def random_prime(bits, rng, stats):
    while True:
        stats["candidates"] += 1
        n = rng.getrandbits(bits) | (1 << (bits - 1)) | 1     # odd, exactly `bits` bits
        if is_probable_prime(n, 40, rng, stats):
            return n

rng = random.Random(2026)
for bits in [64, 256]:
    stats = {"candidates": 0, "mr rounds": 0}
    primes = [random_prime(bits, rng, stats) for _ in range(20)]
    per = stats["candidates"] / 20
    print(f"{bits:3}-bit primes: {per:5.1f} odd candidates per prime (estimate {bits * 0.6931 / 2:5.1f}), "
          f"{stats['mr rounds'] / 20:5.1f} Miller-Rabin rounds per prime")
 64-bit primes:  13.4 odd candidates per prime (estimate  22.2),  43.1 Miller-Rabin rounds per prime
256-bit primes:  86.7 odd candidates per prime (estimate  88.7),  63.7 Miller-Rabin rounds per prime

Each prime costs about 40 full rounds (the final, successful test) plus roughly one round for each candidate that survives trial division, in line with the estimate. (Twenty primes is a small sample, so the averages wobble.)

The full cost

For a β\beta-bit modulus, with schoolbook arithmetic:

Step Work Bit operations
find a β/2\beta/2-bit prime O(β)O(\beta) candidates, each O(1)O(1) Miller-Rabin rounds on average, plus ss rounds at the end O(β4)O(\beta^4) expected
n=pqn = pq, φ=(p−1)(q−1)\varphi = (p-1)(q-1) two multiplications O(β2)O(\beta^2)
d=e−1 mod φd = e^{-1} \bmod \varphi extended Euclid, O(β)O(\beta) steps (Euclid's Algorithm and Its Running Time) O(β2)O(\beta^2)
encrypt or verify, e=65537e = 65537 17 modular multiplications O(β2)O(\beta^2)
decrypt or sign, dd of β\beta bits about 1.5β1.5\beta modular multiplications O(β3)O(\beta^3)

The public operation is cheap because ee is small; the private one is the expensive one. The Chinese remainder theorem speeds it up about four times: compute cd mod (p−1) mod pc^{d \bmod (p-1)} \bmod p and cd mod (q−1) mod qc^{d \bmod (q-1)} \bmod q with half-size numbers and exponents, each costing (β/2)3=β3/8(\beta/2)^3 = \beta^3/8, and combine them (RSA with the CRT).

python · try it yourself
def ext_gcd(a, b):
    if b == 0:
        return a, 1, 0
    d, x, y = ext_gcd(b, a % b)
    return d, y, x - (a // b) * y

def count_mults(exponent):
    return exponent.bit_length() - 1 + bin(exponent).count("1") - 1

# two fixed primes of 127 and 128 bits (checked with Miller-Rabin)
p = 2**127 - 1                                     # a Mersenne prime
q = 340282366920938463463374607431768211297        # 2^128 - 159, also prime
n, phi, e = p * q, (p - 1) * (q - 1), 65537
g, x, _ = ext_gcd(e, phi)
d = x % phi
print("modulus bits:", n.bit_length(), " gcd(e, phi) =", g, " e*d mod phi =", e * d % phi)

m = int.from_bytes(b"work and span", "big")
c = pow(m, e, n)
plain = pow(c, d, n)
print("decrypts correctly:", plain == m, "->", plain.to_bytes(13, "big").decode())

dp, dq, q_inv = d % (p - 1), d % (q - 1), pow(q, -1, p)
mp, mq = pow(c, dp, p), pow(c, dq, q)
crt = mq + q * ((mp - mq) * q_inv % p)
print("CRT decryption agrees:", crt == m)
print("modular multiplications: encrypt", count_mults(e), ", decrypt", count_mults(d),
      f"({d.bit_length()}-bit d), CRT 2 x about {count_mults(dp)} on half-size numbers")
modulus bits: 255  gcd(e, phi) = 1  e*d mod phi = 1
decrypts correctly: True -> work and span
CRT decryption agrees: True
modular multiplications: encrypt 17 , decrypt 375 (255-bit d), CRT 2 x about 189 on half-size numbers

Easy and hard

Everything a key owner does takes polynomial time in β\beta. Breaking the key by factoring nn is believed to be hard: trial division needs about 2β/22^{\beta/2} steps, and the best known classical algorithm, the general number field sieve, runs in time

exp⁡ ⁣((64/93+o(1))(ln⁡n)1/3(ln⁡ln⁡n)2/3),\exp\!\left(\left(\sqrt[3]{64/9} + o(1)\right) (\ln n)^{1/3} (\ln \ln n)^{2/3}\right),

subexponential but far beyond reach for β=2048\beta = 2048. Nobody has proved that factoring is hard, and factoring is not believed to be NP-complete; it lies in NP and in co-NP, and Shor's algorithm factors in polynomial time on a quantum computer. The Post-Quantum Cryptography lesson covers what replaces RSA if large quantum computers are built. The gap between polynomial-time key generation and (apparently) super-polynomial attack is the same gap between P and harder problems that the last section of this course formalizes.

In C++

Toy RSA in C++ with primes just below 2162^{16}, so that n<232n < 2^{32} and every product fits in 64 bits. The primes are found by scanning downward with the deterministic Miller-Rabin test of the previous lesson.

cpp · try it yourself
#include <cstdint>
#include <cstdio>
#include <initializer_list>

uint64_t power_mod(uint64_t a, uint64_t b, uint64_t m) {
    uint64_t r = 1; a %= m;
    for (; b; b >>= 1, a = a * a % m) if (b & 1) r = r * a % m;
    return r;
}

bool is_prime(uint32_t n) {
    if (n < 2) return false;
    for (uint32_t p : {2u, 3u, 5u, 7u}) if (n % p == 0) return n == p;
    uint32_t u = n - 1; int t = 0;
    while (u % 2 == 0) { u /= 2; t++; }
    for (uint64_t a : {2u, 7u, 61u}) {
        if (a % n == 0) continue;
        uint64_t x = power_mod(a, u, n);
        if (x == 1 || x == n - 1) continue;
        bool composite = true;
        for (int i = 1; i < t && composite; i++) { x = x * x % n; if (x == n - 1) composite = false; }
        if (composite) return false;
    }
    return true;
}

int64_t inverse(int64_t a, int64_t m) {                // extended Euclid
    int64_t old_r = a, r = m, old_s = 1, s = 0;
    while (r != 0) {
        int64_t q = old_r / r, tmp;
        tmp = old_r - q * r; old_r = r; r = tmp;
        tmp = old_s - q * s; old_s = s; s = tmp;
    }
    return (old_s % m + m) % m;
}

int main() {
    uint32_t p = 65535, q;
    while (!is_prime(p)) p--;
    q = p - 2;
    while (!is_prime(q)) q--;
    uint64_t n = uint64_t(p) * q, phi = uint64_t(p - 1) * (q - 1), e = 65537;
    uint64_t d = inverse(e, phi);
    std::printf("p = %u, q = %u, n = %llu, d = %llu\n", p, q, (unsigned long long)n, (unsigned long long)d);
    for (uint64_t m : {42ULL, 123456789ULL, 4000000000ULL}) {
        uint64_t c = power_mod(m, e, n);
        std::printf("m = %10llu -> c = %10llu -> %10llu\n", (unsigned long long)m, (unsigned long long)c,
                    (unsigned long long)power_mod(c, d, n));
    }
}
p = 65521, q = 65519, n = 4292870399, d = 1475213633
m =         42 -> c =  777359323 ->         42
m =  123456789 -> c = 2081669972 ->  123456789
m = 4000000000 -> c = 1949122881 -> 4000000000

Test yourself

About how many random odd 1024-bit numbers must be tested, on average, to find a prime?

  1. About 10
  2. About 355
  3. About 1024
  4. About 25122^{512}

Why is RSA encryption with e=65537e = 65537 much cheaper than decryption?

  1. Decryption needs factoring
  2. ee has only 17 bits, so encryption takes 17 modular multiplications, while dd has about β\beta bits
  3. Encryption uses the CRT
  4. Decryption works with larger numbers

Which algorithm computes the private exponent dd from ee and φ(n)\varphi(n)?

  1. Miller-Rabin
  2. The extended Euclidean algorithm
  3. The FFT
  4. Trial division

Roughly how much faster is CRT decryption than plain decryption with schoolbook arithmetic?

  1. 2 times
  2. 4 times
  3. 8 times
  4. No faster