TExcelTAD
Home › Number Theory & Cryptography › Generating Large Primes

Generating Large Primes

An RSA key needs two random 1024-bit (or larger) primes; Diffie-Hellman parameters need a "safe" prime. This lesson puts the previous ones together: pick random candidates, sieve out small factors, run Miller-Rabin, and check the extra conditions standards demand.

The basic loop

  1. Pick a random kk-bit odd number: set the top bit (so it really has kk bits) and the bottom bit (odd). Standards also set the second-highest bit so that p⋅qp \cdot q has exactly 2k2k bits.
  2. Reject it if a small prime divides it.
  3. Run Miller-Rabin; if it passes, accept.

By the prime number theorem about 1 in kln⁡2/2k \ln 2 / 2 odd candidates is prime, so a 512-bit search takes about 180 candidates on average.

Warning: The code below uses random.Random(seed) so the output is reproducible. That generator is predictable and must never produce real keys. Real key generation draws from the operating system's CSPRNG (secrets in Python) (Secure Random Numbers).

python · try it yourself
import random

SMALL_PRIMES = [p for p in range(3, 1000) if all(p % q for q in range(2, int(p**0.5) + 1))]

def mr_round(n, a):
    d, s = n - 1, 0
    while d % 2 == 0:
        d, s = d // 2, s + 1
    x = pow(a, d, n)
    if x in (1, n - 1):
        return True
    for _ in range(s - 1):
        x = x * x % n
        if x == n - 1:
            return True
    return False

def gen_prime(bits, rng, rounds=20):
    tried = 0
    while True:
        n = rng.getrandbits(bits) | (1 << (bits - 1)) | (1 << (bits - 2)) | 1
        tried += 1
        if any(n % p == 0 for p in SMALL_PRIMES):
            continue
        if all(mr_round(n, rng.randrange(2, n - 1)) for _ in range(rounds)):
            return n, tried

rng = random.Random(2026)          # teaching only: reproducible, NOT secure
p, tried = gen_prime(512, rng)
print(p.bit_length(), "bits, candidates tried:", tried)
print(str(p)[:40] + "...")
512 bits, candidates tried: 278
1191767132993887329044114667246474645437...

This run needed 278 draws (most were thrown out by the cheap small-prime check), within the normal spread around the average.

Incremental search

Generating fresh random numbers is wasteful; many libraries instead pick one random odd start n0n_0 and test n0,n0+2,n0+4,…n_0, n_0 + 2, n_0 + 4, \ldots, keeping a table of n0 mod pn_0 \bmod p for small primes so that the sieve step costs one addition per small prime. The catch: primes that follow long gaps are chosen more often, a slight bias that is considered harmless.

python · try it yourself
import random

def small_sieve_search(bits, rng):
    smalls = [p for p in range(3, 2000) if all(p % q for q in range(2, int(p**0.5) + 1))]
    n0 = rng.getrandbits(bits) | (1 << (bits - 1)) | 1
    rems = [n0 % p for p in smalls]
    offset, survivors = 0, 0
    while True:
        if all((r + offset) % p for r, p in zip(rems, smalls)):
            survivors += 1
            n = n0 + offset
            if pow(2, n - 1, n) == 1 and pow(3, n - 1, n) == 1:     # quick check; use MR for real
                return offset // 2, survivors
        offset += 2

print(small_sieve_search(256, random.Random(7)))
(21, 5)

The first number is how many odd candidates were stepped over, the second how many survived the sieve and needed an exponentiation: sieving saves most of the expensive work.

Safe primes

A safe prime is p=2q+1p = 2q + 1 with qq also prime (qq is then a Sophie Germain prime). In Zp×\mathbb{Z}_p^\times the only subgroup orders are 1, 2, qq and 2q2q, which defeats Pohlig-Hellman and small-subgroup attacks. Safe primes are much rarer (both qq and 2q+12q + 1 must be prime), so generating them is slow, which is why protocols use fixed published groups (RFC 3526, RFC 7919).

python · try it yourself
from sympy import isprime

safe = [p for p in range(5, 2000) if isprime(p) and isprime((p - 1) // 2)]
print(len(safe), safe[:15])
37 [5, 7, 11, 23, 47, 59, 83, 107, 167, 179, 227, 263, 347, 359, 383]

RSA-specific checks

FIPS 186-5 also requires ∣p−q∣>2k−100\lvert p - q \rvert > 2^{k - 100} for kk-bit primes (to stop Fermat factoring), gcd⁡(e,p−1)=1\gcd(e, p - 1) = 1, and that dd is not too small. Real implementations add these checks to the loop.

In software

  • Python: cryptography.hazmat.primitives.asymmetric.rsa.generate_private_key(65537, 2048); OpenSSL: BN_generate_prime_ex; Go: crypto/rand.Prime.
  • In 2017 the ROCA flaw (CVE-2017-15361) hit Infineon smart cards: their fast prime generator produced primes of a special structured form, letting attackers factor 2048-bit keys. Structure in primes is dangerous; uniform randomness is the requirement.

Exercises

Exercise 1: Expected work

About how many random odd 2048-bit candidates must be tested to find one prime?

Answer

About 710.

Solution

Density among all numbers is about 1/(2048ln⁡2)≈1/14201/(2048 \ln 2) \approx 1/1420; among odd numbers twice that, about 1/7101/710.

Exercise 2: Why set the top two bits?

If pp and qq are 1024-bit primes with the top two bits set, how many bits does pqpq have?

Answer

Exactly 2048.

Solution

With the top two bits set, p,q≥21023+21022=1.5⋅21023p, q \ge 2^{1023} + 2^{1022} = 1.5 \cdot 2^{1023}, so pq≥2.25⋅22046>22047pq \ge 2.25 \cdot 2^{2046} > 2^{2047}. And pq<22048pq < 2^{2048}. Setting only the top bit could give a 2047-bit product.

Exercise 3: Sophie Germain primes (code)

Count safe primes below 100000 and compare with the number of primes.

Answer

670 safe primes against 9592 primes.

Solution
python · try it yourself
from sympy import isprime, primepi
safe = sum(1 for p in range(5, 100000, 2) if isprime(p) and isprime((p - 1) // 2))
print(safe, int(primepi(100000)))
670 9592

Safe primes thin out like 1/(ln⁡x)21/(\ln x)^2 instead of 1/ln⁡x1/\ln x.

Test yourself

Why do prime generators sieve candidates with small primes before Miller-Rabin?

  1. it makes the primes stronger
  2. it cheaply discards most composites before the expensive exponentiation
  3. Miller-Rabin cannot handle even numbers
  4. it is required by RSA math

A safe prime is…

  1. any prime above 210242^{1024}
  2. p=2q+1p = 2q + 1 with qq prime
  3. a prime ending in 7
  4. a Mersenne prime

Which source of randomness must generate real RSA primes?

  1. random.Random(seed)
  2. a cryptographically secure generator such as the OS CSPRNG
  3. the current time
  4. a fixed counter