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
- Pick a random -bit odd number: set the top bit (so it really has bits) and the bottom bit (odd). Standards also set the second-highest bit so that has exactly bits.
- Reject it if a small prime divides it.
- Run Miller-Rabin; if it passes, accept.
By the prime number theorem about 1 in 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 (secretsin Python) (Secure Random Numbers).
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 and test , keeping a table of 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.
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 with also prime ( is then a Sophie Germain prime). In the only subgroup orders are 1, 2, and , which defeats Pohlig-Hellman and small-subgroup attacks. Safe primes are much rarer (both and must be prime), so generating them is slow, which is why protocols use fixed published groups (RFC 3526, RFC 7919).
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 for -bit primes (to stop Fermat factoring), , and that 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 ; among odd numbers twice that, about .
Exercise 2: Why set the top two bits?
If and are 1024-bit primes with the top two bits set, how many bits does have?
Answer
Exactly 2048.
Solution
With the top two bits set, , so . And . 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
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 instead of .
Test yourself
Why do prime generators sieve candidates with small primes before Miller-Rabin?
- it makes the primes stronger
- it cheaply discards most composites before the expensive exponentiation
- Miller-Rabin cannot handle even numbers
- it is required by RSA math
A safe prime is…
- any prime above
- with prime
- a prime ending in 7
- a Mersenne prime
Which source of randomness must generate real RSA primes?
random.Random(seed)- a cryptographically secure generator such as the OS CSPRNG
- the current time
- a fixed counter