TExcelTAD
Home › Applied Cryptography: Ciphers, Hashes, Signatures, PKI & TLS › Secure Randomness: CSPRNG versus random

Secure Randomness: CSPRNG versus random

Every key, nonce, salt, session id, password-reset token and CSRF token in this course starts as random bytes. If an attacker can predict those bytes, the cryptography on top doesn't matter: the 2008 Debian OpenSSL bug left 32,768 possible keys, the 2012 embedded-device study found RSA keys sharing primes, the PS3 and Android wallet breaks came from repeated ECDSA nonces. Getting randomness right is mostly about one decision: use the operating system's cryptographically secure generator, never a general-purpose one.

Two kinds of generator

random (Mersenne Twister, MT19937) secrets / os.urandom (OS CSPRNG)
designed for simulations, games, sampling, reproducible tests keys, tokens, nonces, salts
seedable and reproducible yes, which is the point no
predictable from outputs yes: 624 outputs of 32 bits reveal the whole state no, by design
source an algorithm and a seed the kernel's generator, fed by hardware events and CPU entropy, reseeded continuously

A CSPRNG (cryptographically secure pseudorandom number generator) must make its output indistinguishable from random, and knowing past outputs must not help predict future ones. On Linux, os.urandom and secrets call getrandom(), which reads the kernel's ChaCha20-based generator; on Windows they use BCryptGenRandom; browsers expose crypto.getRandomValues. NIST SP 800-90A/B/C describe the approved designs (DRBGs) and entropy sources.

Breaking a token generator built on random

The toy service in the first example (it exists only inside the example) seeds random with its start date and issues reset tokens. The attacker requests a reset for their own account, gets one token, and tries every date in 2026 as the seed.

python · try it yourself
import random, secrets, math

# A toy service, made by this example, that issues password-reset tokens with the `random` module,
# seeded with the date it started (a guessable seed).
service = random.Random(20260115)
issued = ["%08x" % service.getrandbits(32) for _ in range(3)]
print("tokens issued:", issued)

# The attacker gets one token (their own reset) and tries every date of 2026 as the seed.
for day in range(20260101, 20261232):
    clone = random.Random(day)
    if "%08x" % clone.getrandbits(32) == issued[0]:
        print("seed found:", day)
        print("predicted next tokens:", ["%08x" % clone.getrandbits(32) for _ in range(2)])
        break

# Even without a guessable seed, Mersenne Twister is not secure: its state is 624 words of 32 bits,
# and 624 consecutive outputs determine it completely.
print("MT19937 state words:", len(random.getstate()[1]) - 1)

# The fix: the operating system's CSPRNG through `secrets`
t = secrets.token_urlsafe(32)
print("secrets.token_urlsafe(32):", len(t), "characters from 32 bytes =", 32 * 8, "bits")
print("6-digit code:", round(math.log2(10**6), 1), "bits; use secrets.randbelow(10**6) and rate limiting")
tokens issued: ['ec7a75ef', 'd466616f', '3fdb8258']
seed found: 20260115
predicted next tokens: ['d466616f', '3fdb8258']
MT19937 state words: 624
secrets.token_urlsafe(32): 43 characters from 32 bytes = 256 bits
6-digit code: 19.9 bits; use secrets.randbelow(10**6) and rate limiting

The attacker now knows the next two tokens, the ones sent to other users. Seeding from the time, the process id or a counter gives an attacker a small space to search; Netscape's SSL in 1995 seeded from the time and process ids, and Ian Goldberg and David Wagner recovered session keys in under a minute.

A secret seed doesn't save random either. MT19937's output is its internal state passed through an invertible "tempering" step, so 624 consecutive 32-bit outputs give back the state. The second example does that against a generator with a seed the attacker never sees:

python · try it yourself
import random

def untemper(y):                                   # invert MT19937's output tempering
    y ^= y >> 18
    y ^= (y << 15) & 0xEFC60000
    x = y
    for _ in range(5): x = y ^ ((x << 7) & 0x9D2C5680)
    y = x
    x = y
    for _ in range(3): x = y ^ (x >> 11)
    return x & 0xffffffff

victim = random.Random(987654321)                  # the toy service's generator; seed unknown to the attacker
outputs = [victim.getrandbits(32) for _ in range(624)]   # 624 observed 32-bit outputs
state = [untemper(o) for o in outputs]
clone = random.Random()
clone.setstate((3, tuple(state + [624]), None))    # rebuild the generator from the observed outputs
print("next 3 from victim:", [victim.getrandbits(32) for _ in range(3)])
print("next 3 from clone :", [clone.getrandbits(32) for _ in range(3)])
next 3 from victim: [1082499909, 2696097902, 49811163]
next 3 from clone : [1082499909, 2696097902, 49811163]

The clone predicts every future output. Python's documentation says it plainly: the random module "should not be used for security purposes".

Where real systems lose randomness

  • Wrong API: random, Math.random(), rand(), java.util.Random, mt_rand() for tokens; uuid.uuid1() (time and MAC address) as a secret.
  • Early boot and cloned machines: embedded devices generating keys before the kernel has collected entropy (the 2012 shared-primes study); VM snapshots and container images restored many times with the same generator state in user-space libraries.
  • Forks: a user-space generator copied into a child process produces the same stream in parent and child unless it reseeds (an OpenSSL and LibreSSL issue in the past).
  • Bias: secrets.token_bytes(1)[0] % 6 is not uniform (256 isn't a multiple of 6); use secrets.randbelow(6) or secrets.choice.
  • Backdoored or weak designs: the Dual_EC_DRBG standard (withdrawn by NIST in 2014) had a structure allowing whoever chose its constants to predict outputs.
  • Too few bits: a 6-digit code has only 19.9 bits; it is safe only with rate limiting and short expiry.

How weak randomness is detected

  • Code review and static analysis: import random in code that creates tokens, passwords, keys, salts or nonces (Bandit rule B311, Semgrep rules for Math.random in security contexts); seed( with time or constants in production code.
  • Token analysis of your own application: collect many tokens and check length, alphabet and uniqueness; Burp Sequencer runs statistical tests (in an authorised test); look for timestamps or counters inside tokens.
  • Key inventories: batch GCD over RSA moduli, duplicate ECDSA r values, duplicate keys across devices.
  • Boot-time behaviour on embedded devices: keys generated on first boot before getrandom() would unblock.

How it is fixed

  • Python: secrets.token_bytes(32), secrets.token_urlsafe(32), secrets.randbelow(n), secrets.choice(seq), os.urandom(n). Libraries such as cryptography already use the OS generator for keys and nonces.
  • Other platforms: crypto.getRandomValues / crypto.randomUUID() (browsers, Node), java.security.SecureRandom, crypto/rand (Go), getrandom() or /dev/urandom (C on Linux), random_bytes() (PHP).
  • At least 128 bits for anything that must not be guessed; 256 bits for long-lived keys.
  • On devices: provision keys at manufacturing or wait for the kernel's entropy before generating them; use a hardware RNG feeding the kernel.

Pitfalls

  • Using /dev/random "because it is more random": on modern Linux both give the same CSPRNG output; /dev/random merely blocks until the pool is initialised, which getrandom() also does.
  • Hashing a weak seed ("SHA-256 of the time") and believing the output is strong: hashing doesn't add entropy.
  • Reproducible tests that accidentally ship: a fixed random.seed(0) left in production code. (This course fixes keys and seeds only in examples, and says so.)

Practice

1. A reset token is md5(str(time.time())). How would you assess it, and what is the fix?

The input is a timestamp with microsecond resolution at best; an attacker who knows roughly when a reset was requested searches a window of seconds, about 10^6 to 10^7 candidates per second of uncertainty, which is fast. Fix: secrets.token_urlsafe(32), stored as a hash with an expiry, single use.

2. Why can the clone in the second example predict outputs although the seed was never revealed?

Mersenne Twister's output is a reversible function of its 624-word state; untempering 624 consecutive outputs recovers the state, and the generator is deterministic from there.

3. Is secrets.token_hex(4) enough for a session id?

No: 4 bytes are 32 bits, about 4 billion values, which an attacker can enumerate or hit by chance across many sessions. Use at least 16 bytes (128 bits), e.g. secrets.token_urlsafe(32).

Test yourself

Which Python API should generate a password-reset token?

  1. random.getrandbits(128)
  2. secrets.token_urlsafe(32)
  3. uuid.uuid1()
  4. hash(time.time())

How many consecutive 32-bit outputs of MT19937 determine its entire state?

  1. 1
  2. 64
  3. 624
  4. It can't be determined

Why is secrets.token_bytes(1)[0] % 6 a bad die roll?

  1. It is predictable
  2. 256 is not a multiple of 6, so some values are more likely
  3. It is too slow
  4. It returns bytes

What caused the 2008 Debian OpenSSL vulnerability?

  1. A weak cipher
  2. A patch that removed most entropy from the random generator, leaving 32,768 possible keys
  3. A padding oracle
  4. SHA-1 collisions