TExcelTAD
Home › Number Theory & Cryptography › Secure Random Numbers

Secure Random Numbers

Every key, nonce, salt and RSA prime in this course starts as random bits. If those bits are predictable, the strongest mathematics is irrelevant: Debian's 2008 OpenSSL bug (CVE-2008-0166) left only 32768 possible SSH keys of each type and size, and Android's 2013 random-number flaw let thieves recompute ECDSA nonces. This lesson explains the difference between a statistical PRNG and a cryptographically secure one, and breaks Python's random module to prove it.

Two kinds of generators

Statistical PRNG CSPRNG
Examples Mersenne Twister (random), LCGs, xorshift, PCG OS generator (/dev/urandom, getrandom, BCryptGenRandom), ChaCha20-based DRBGs
Goal good statistics, speed, reproducibility unpredictable, even given previous outputs
Use simulations, games, tests keys, tokens, nonces, salts, passwords

A cryptographically secure generator must pass the next-bit test: no efficient algorithm, given any number of outputs, predicts the next bit with probability noticeably above 1/2.

Breaking the Mersenne Twister

Python's random uses MT19937. Its state is 624 words of 32 bits, and each output is a reversible "tempering" of one state word. So 624 consecutive 32-bit outputs reveal the whole state, and every future output.

python · try it yourself
import random

victim = random.Random(20260611)           # stands in for an unknown seed
observed = [victim.getrandbits(32) for _ in range(624)]

def untemper(y):
    y ^= y >> 18
    y ^= (y << 15) & 0xEFC60000
    t = y
    for _ in range(5):                      # undo y ^= (y << 7) & mask
        t = y ^ ((t << 7) & 0x9D2C5680)
    y = t & 0xFFFFFFFF
    t = y
    for _ in range(3):                      # undo y ^= y >> 11
        t = y ^ (t >> 11)
    return t & 0xFFFFFFFF

state = [untemper(v) for v in observed]
clone = random.Random()
clone.setstate((3, tuple(state + [624]), None))
predicted = [clone.getrandbits(32) for _ in range(5)]
actual = [victim.getrandbits(32) for _ in range(5)]
print("predicted:", predicted)
print("actual:   ", actual)
print("match:", predicted == actual)
predicted: [3671506998, 2664111680, 3083370842, 2483871933, 1900579265]
actual:    [3671506998, 2664111680, 3083370842, 2483871933, 1900579265]
match: True

An attacker who sees 624 session tokens from a server using random can mint all future tokens. The same goes for LCGs, which fall after three outputs.

Using the right tool

Python's secrets module (and os.urandom) reads the operating system's CSPRNG, which is seeded from hardware events and re-keyed continuously.

python · try it yourself
import secrets, os, string

token = secrets.token_bytes(32)
url_token = secrets.token_urlsafe(16)
alphabet = string.ascii_letters + string.digits
password = "".join(secrets.choice(alphabet) for _ in range(20))
print(len(token), len(url_token), len(password))
print(0 <= secrets.randbelow(10**6) < 10**6, len(os.urandom(16)))
32 22 20
True 16

(The values themselves change on every run, so only their lengths are printed.)

Avoiding modulo bias

Turning random bytes into a number below nn with x % n is biased unless nn divides the range. With one byte (0..255) and n=100n = 100, the values 0..55 occur 3 times and 56..99 only twice. ECDSA nonces with such a bias have been broken with lattice attacks. The fix is rejection sampling, which secrets.randbelow does internally.

python · try it yourself
from collections import Counter

counts = Counter(b % 100 for b in range(256))      # every byte value once
print("value 10 occurs", counts[10], "times, value 90 occurs", counts[90], "times")

def unbiased_below(n, byte_source):
    limit = 256 - 256 % n                           # largest multiple of n not above 256
    for b in byte_source:
        if b < limit:
            return b % n                           # reject the biased tail

print(unbiased_below(100, iter([250, 203, 17])))   # 250 and 203 are rejected
value 10 occurs 3 times, value 90 occurs 2 times
17

Where entropy comes from

The OS mixes interrupt timings, hardware RNG instructions (RDRAND/RDSEED), device noise and boot-time seeds into a pool, then expands it with a cryptographic DRBG (ChaCha20 in Linux since 5.17, AES-CTR-DRBG in many others). Problems arise when systems generate keys before enough entropy is collected, for example embedded devices at first boot. That is how the 2012 study found RSA keys with shared primes (GCD and Euclid's Algorithm).

In software

  • Python: secrets, never random, for anything security-related. JavaScript: crypto.getRandomValues, never Math.random. Java: SecureRandom. Go: crypto/rand. Rust: rand::rngs::OsRng or the getrandom crate.
  • For reproducible simulations (this site's examples), seeded statistical generators like np.random.default_rng(seed) are the right choice, precisely because they are predictable.

Exercises

Exercise 1: Which generator?

Choose a generator for: (a) a password-reset token; (b) shuffling enemies in a game level; (c) a Monte Carlo simulation that must be reproducible; (d) an AES-GCM nonce.

Answer

(a) CSPRNG, (b) statistical PRNG, (c) seeded statistical PRNG, (d) CSPRNG or a counter.

Solution

Anything an attacker must not predict (tokens, keys, nonces) needs a CSPRNG; GCM nonces may also be a counter, as long as they never repeat. Games and simulations want speed and reproducibility.

Exercise 2: Debian's bug

The 2008 Debian OpenSSL bug seeded the generator only with the process ID (at most 32768 values). How many SSH keys of each type and size could the affected systems generate?

Answer

At most 32768.

Solution

A deterministic generator with one of 32768 seeds can produce at most 32768 different outputs, so attackers precomputed every possible key and matched public keys against the list.

Exercise 3: Measure the bias (code)

Compute the probability of 0 and of 99 when a random 16-bit number is reduced modulo 100. How large is the bias?

Answer

656/65536 versus 655/65536: tiny but nonzero.

Solution
python · try it yourself
from collections import Counter
c = Counter(x % 100 for x in range(2**16))
print(c[0], c[99], c[0] / 2**16 - c[99] / 2**16)
656 655 1.52587890625e-05

With more random bits the bias shrinks, but for secret nonces even tiny biases accumulate over many signatures; rejection sampling removes it entirely.

Go further: Secure Randomness: CSPRNG versus random breaks a token generator built on random.

Test yourself

Which Python module should generate session tokens?

  1. random
  2. secrets
  3. numpy.random
  4. time

How many 32-bit outputs of MT19937 reveal its full state?

  1. 1
  2. 32
  3. 624
  4. 2199372^{19937}

Reducing a random byte modulo 100 is biased because…

  1. 100 is even
  2. 256 is not a multiple of 100, so small values occur once more often
  3. bytes are signed
  4. it is not biased