PRNG Attacks
A pseudo-random generator is a deterministic function with a finite state. Given enough of its output, the state is recoverable, and every future value it produces becomes known. The attack is not a break of any cipher — it is a bookkeeping failure where a token, a key, or a nonce was drawn from the wrong kind of generator.
Predictable is not the same as weak
Where randomness fails
Three distinct failures get reported under the same heading, and they need different evidence:
A non-cryptographic generator used for a secret
The most common and the most exploitable. random.random(),
Math.random(),
java.util.Random.
Fast, seeded once, and fully recoverable from its own output.
A cryptographic generator seeded from a guessable value
A CSPRNG seeded with a timestamp, a process ID, or a counter collapses to the size of its seed. The primitive is right and the entropy is wrong, which makes it harder to see in review and easier to exploit in practice.
A secure source truncated to too few bits
random_int(0, 999999)
is 20 bits. Correctly generated, still brute-forced in a million requests — and the difference between this and
the two above is that this one is a design decision, not a bug.
The table below is the practical index. State size determines how much output an attacker needs, and that number is the difference between a finding you can demonstrate and one you can only assert.
| Runtime | API | Algorithm | State | Recovery |
|---|---|---|---|---|
| Python | random.random(), random.getrandbits() | MT19937 (Mersenne Twister) | 624 x 32-bit words | 624 consecutive 32-bit outputs, untempered |
| PHP | mt_rand(), rand() (since 7.1) | MT19937 with a 32-bit seed | 624 x 32-bit words, seeded from 32 bits | php_mt_seed brute-forces the seed from 1-2 outputs |
| Java | java.util.Random.nextInt() | 48-bit linear congruential generator | 48 bits | 2 consecutive nextInt() or 1 nextLong() |
| .NET | System.Random (legacy implementation) | Subtractive generator, 56-element array | ~55 x 32-bit words | 55 consecutive outputs for the legacy algorithm |
| JavaScript | Math.random() in V8 | xorshift128+ | 128 bits | A run of consecutive doubles from the same engine instance |
MT19937
MT19937 is the generator behind Python's random
module and PHP's mt_rand.
Its state is 624 32-bit words. Each output is a state word passed through a fixed tempering function — three shifts
with masks and one final right shift, all invertible. Recover 624 consecutive outputs, invert the tempering, and
you have the state.
The inversion is arithmetic, not a solver. Each of the four operations is a shift-xor, and each is invertible by iterating the same expression until it converges — five rounds is more than enough for 32 bits. Solving it with an SMT solver is a common mistake in write-ups: it is slower, it needs the exact tempering constants restated, and it fails silently when a constraint is off by one, where the direct inversion either reproduces the state or does not.
import random
MASK = 0xFFFFFFFF
def unshift_right(y, shift):
"""Invert y ^= y >> shift, which is lossy on its own but converges."""
x = y
for _ in range(5):
x = y ^ (x >> shift)
return x & MASK
def unshift_left(y, shift, mask):
"""Invert y ^= (y << shift) & mask."""
x = y
for _ in range(5):
x = y ^ ((x << shift) & mask)
return x & MASK
def untemper(y):
"""Invert MT19937 tempering. The order of the inverses is reversed."""
y = unshift_right(y, 18)
y = unshift_left(y, 15, 0xEFC60000)
y = unshift_left(y, 7, 0x9D2C5680)
y = unshift_right(y, 11)
return y
outputs = [int(line) for line in open("outputs.txt")] # 624 x getrandbits(32)
assert len(outputs) >= 624, "MT19937 needs 624 words, not 624 random() calls"
state = [untemper(o) for o in outputs[:624]]
clone = random.Random()
clone.setstate((3, tuple(state + [624]), None))
# verify before predicting: the next value the server produced must match
print(clone.getrandbits(32))624 outputs, not 624 calls
random.getrandbits(32)
is one word per call. random.random()
consumes two words and returns 53 bits, so 624 calls give you 1,248 words with 11 bits discarded from
each pair — enough in practice to reconstruct, but the recovery is a different exercise.
getrandbits(k) for k
above 32 consumes ceil(k/32) words.
The cloning step matters as much as the recovery. Python lets you install a recovered state directly, which is why the verification line in the script above is the whole test: if the cloned generator reproduces the next value the server produced, the state is right. If it does not, one of the four inversions is wrong and the prediction that follows is noise.
Java and PHP
Neither needs 624 outputs, and both are recovered differently. PHP's mt_rand
is MT19937 seeded from 32 bits, so the state is easier to brute-force through the seed than to recover through the
output. Java's java.util.Random
is a 48-bit linear congruential generator, and nextInt()
returns the top 32 bits of that state — leaving 16 unknown, which is 65,536 candidates.
# PHP: the seed is 32 bits, so brute force beats state recovery.
# Collect one mt_rand() output, then:
php_mt_seed 1234567890
# The tool prints candidate seeds; confirm one by running the same
# mt_srand() and checking the next two outputs match the server's.
# Java: 48-bit LCG, so one nextInt() leaves only 16 unknown bits.
# nextInt() returns the top 32 bits of the 48-bit state.
# Brute the low 16 bits, keep the candidate that reproduces output two.
python3 - <<'PY'
from itertools import count
A, C, M = 0x5DEECE66D, 0xB, (1 << 48) - 1
o1, o2 = 1234567890, 987654321 # two consecutive nextInt() values
for low in range(1 << 16):
seed = (o1 << 16) | low
nxt = (seed * A + C) & M
if nxt >> 16 == o2:
print("state:", hex(seed))
PY| Generator | What one output reveals | Work to recover | Practical consequence |
|---|---|---|---|
| PHP mt_rand | Behaviour of one 32-bit seed | Seconds on a laptop, via php_mt_seed | Reset tokens from the request time are forged directly |
| java.util.Random | 32 of 48 state bits | 65,536 candidates, one arithmetic check each | Session IDs and CSRF tokens become predictable within one request |
| .NET legacy Random | Part of a subtractive array | 55 consecutive outputs | Guid.NewGuid is separate and fine; Random is not |
| V8 Math.random | 52 bits of a 128-bit xorshift state | A short run of consecutive doubles | Client-side tokens generated in the browser are readable and predictable |
Seed recovery
When the state is large but the seed is small, attacking the seed is cheaper than attacking the state. This is the second failure mode in the list above, and it is what makes a correctly-chosen CSPRNG still predictable: if the application seeds it from the clock, the entropy is the clock's, not the generator's.
The search space is usually small enough to enumerate. A millisecond timestamp in a known hour is 3.6 million
candidates; add the PID and it is still one afternoon on a GPU. The tell in code review is a seed argument built
from anything in time,
Date,
process.pid, or a
counter.
import random
import string
# Seeded from the process clock at first use. An attacker who can read
# one token can reconstruct the generator and predict the next reset link.
def reset_token():
alphabet = string.ascii_letters + string.digits
return "".join(random.choices(alphabet, k=32))import random
import string
# Seeded from the process clock at first use. An attacker who can read
# one token can reconstruct the generator and predict the next reset link.
def reset_token():
alphabet = string.ascii_letters + string.digits
return "".join(random.choices(alphabet, k=32))import secrets
def reset_token():
# 32 bytes from the OS CSPRNG, URL-safe encoding.
# 256 bits of entropy; no state to recover, no seed to guess.
return secrets.token_urlsafe(32)
# Equivalents:
# Java SecureRandom.getInstanceStrong() / new SecureRandom()
# Node crypto.randomBytes(32).toString("base64url")
# PHP random_bytes(32) then base64/bin2hex, or random_int()
# .NET RandomNumberGenerator.GetBytes(32)
# Go crypto/rand, never math/randimport secrets
def reset_token():
# 32 bytes from the OS CSPRNG, URL-safe encoding.
# 256 bits of entropy; no state to recover, no seed to guess.
return secrets.token_urlsafe(32)
# Equivalents:
# Java SecureRandom.getInstanceStrong() / new SecureRandom()
# Node crypto.randomBytes(32).toString("base64url")
# PHP random_bytes(32) then base64/bin2hex, or random_int()
# .NET RandomNumberGenerator.GetBytes(32)
# Go crypto/rand, never math/randToken prediction
The attack that matters is rarely the generator. It is the flow that trusts it: a password reset link built from a predictable value, a session identifier assigned before login, an invitation code that also encodes the tenant. Each of these turns a one-line code defect into account takeover, and each is worth checking even when the generator itself is sound.
| Flow | What must be unpredictable | Common defect |
|---|---|---|
| Password reset | The token in the link | A timestamp hash, or an MT19937 string of 8 characters |
| Pre-login session | The session identifier, before any credential is checked | Sequential IDs, or a PRNG seeded at process start |
| Invitation and referral codes | The code, if redeeming it grants access or credit | Encoding the account id or a counter with a fixed alphabet |
| File and upload names | The name, if the file is reachable by URL | Math.random in the browser, plus a guessable directory |
Mitigation
There is no parameter to tune and no configuration to harden. The generator has to change, and the length has to be chosen for the threat rather than for readability. Below is what that looks like in the languages this section covers:
The rule
Any value an attacker must not guess comes from the operating system, not from a language runtime's general
purpose generator: secrets,
crypto/rand,
SecureRandom,
random_bytes,
RandomNumberGenerator.
Minimum 128 bits for a reset or session token.
The part that is not about randomness
A correct generator plus a token that never expires is still a finding. Single use, short lifetime, and binding to the account and the request are what limit the damage when a token leaks by any other route — logs, referrers, shared browsers.
Detection, afterwards
Predictable-token abuse looks like a burst of redemptions from one source against tokens that were never issued, which is a different signature from brute force. Alert on the redemption failures, not only on the successes — the failures are the attack becoming visible.
| Check | Expected | Where to look |
|---|---|---|
| The generator is identified by call site, not by name | A reported "secure token" traces to a crypto API, or the finding stands | The sink, usually a token or reset-link builder |
| Enough outputs were collected to meet the algorithm state size | 624 words for MT19937, 2 for Java Random, 1 seed for PHP mt_rand | Collection script and count |
| The recovered state reproduces a known later value | The clone prints the next observed output exactly, before it is used to predict anything | Verification step |
| Predictability is tied to a real impact | A guessable reset token that grants account access, not a guessable nonce nobody reads | The finding description |
| The fix changes the generator, not the encoding | CSPRNG plus sufficient length; hashing a timestamp does not help | The patch |
What to Capture
Predictability is only a finding if it reaches something that matters. Capture the chain, not the generator:
The call site: The exact function that produced the value. A module named secure that calls random.random is the finding; the module name is not evidence.
The value in transit: The response that carries it and the route that later accepts it. A token nobody can redeem is not a vulnerability.
The sample count and the proof: How many outputs were collected and the clone reproducing one of them. Without the reproduction step, the claim is a code-review opinion.
The redeemable window: Whether the token is single-use, expiring, and bound to a user. Predictability plus a 15-minute single-use window is a real-time race, not a trivial takeover.
The entropy estimate: Bits, not characters. 32 characters from a 62-symbol alphabet chosen by MT19937 is not 190 bits — it is the state of the generator.
Not Every random Is a Finding
Four cases that look like weak randomness and are not:
- Non-security use: Jitter, sampling, retry delays, test fixtures, load-balancer weights. If guessing the value grants nothing, the generator is irrelevant.
- A CSPRNG behind a familiar name: random.SystemRandom, crypto/rand, SecureRandom, random_int. The wrapper name is the whole argument; read the import before reporting.
- UUIDv4: 122 random bits from the OS, with the version and variant nibbles fixed. Known structure is not predictability.
- Predictable but bounded: A CSRF token that an attacker can only influence within one session, with no cross-user effect, is not the same class of finding as a password reset link.
Randomness Checklist
Work top to bottom; the first three decide whether the rest is worth doing:
- ☐ What is the value used for, and who can observe or redeem it
- ☐ Which function produced it, read from the import not the variable name
- ☐ What is the algorithm and state size for that API and runtime version
- ☐ Collected at least the state size in outputs, consecutively, from one instance
- ☐ Recovered the state and reproduced a later value the server produced
- ☐ Checked the token is accepted somewhere, and how long it stays valid
- ☐ Entropy stated in bits with the reasoning, not characters
- ☐ Impact described as the flow that breaks: account takeover, reset poisoning, session prediction
- ☐ Fix names the CSPRNG API for each affected language, and the length or bits required
Fixes That Hold
The only fix is a different primitive. Everything else is theatre:
Why a longer token from a weak generator is not a fix
Length adds entropy only if each character is independently unpredictable. A 64-character string drawn from MT19937 has at most the state of that generator behind it — 19,937 bits of period, but only 624 words of recoverable state, and an attacker who has seen 624 words knows all 64 characters before they are generated. The same applies to concatenating several weak values: the joined string is one deterministic stream, not independent samples. What actually adds uncertainty is a generator whose state an attacker cannot observe and whose seed they cannot guess, which is why the fix is the API rather than the length.
Reading a token's length as a security claim
A common review shortcut is to compute characters x log2(alphabet) and call that the entropy. That number is an
upper bound and it is only reachable if the source is a CSPRNG. When the source is a PRNG the real entropy is the
state size — or the seed size, if the seed is guessable — whichever is smaller. This is why
random_int(0, 10**12)
is a 40-bit token and also a million-request brute force, while 16 bytes from
secrets is 128
bits that cannot be attacked at all. State the source and the bits together; either one alone is not a security
property.
Randomness Practice
Exercises that start from an output stream and end with a prediction — the only form of this finding that a reviewer can defend.
Related Cryptography Guides
Key Management
The other half of the same problem: secrets that are strong but stored where they leak.
Weak Crypto
Fixed, broken primitives — the adjacent failure mode to a primitive that is simply the wrong kind.
Crypto Fundamentals
Why a cipher needs a random key and an unpredictable IV, and what predictable randomness does to both.
Web Penetration Testing
Where predictable tokens turn into account takeover: session handling and password reset flows.