Pseudo-random versus crypto-secure: which one your feature needs
A password reset link was generated with Math.random(). The seed had 32 bits of entropy, which is four billion possibilities. An attacker needed one guess per few milliseconds to find the token and take over the account, and reset-token enumeration is a documented real-world exploit pattern, not a lab exercise. The function did nothing wrong. It was asked to do the wrong job.
What pseudo-random actually means
A PRNG is math, not dice. It starts with a seed and advances through a deterministic sequence: same seed, same next values, every time. That determinism is a feature in simulations and tests, where a repeatable run saves hours of debugging. It is a defect the moment anyone can benefit from knowing the next value before you do.
The two ways predicting becomes easy
- A small seed space. Seed a generator with the current time, or with anything short, and the attacker tries all plausible seeds and replays your sequence. 32 bits is minutes on a laptop.
- A known internal state. The classic Mersenne Twister, which powers
Math.randomin JavaScript and Python'srandommodule, reveals its full internal state after 624 consecutive outputs. Feed an attacker 624 draws from the same generator your reset tokens come from, and every future value is predicted.
Where Math.random is genuinely the right call
Anything where the value only has to feel scattered. A dice roller, a coin flip, mock data for a demo, sampling a few rows for a manual spot check, the shuffle order in a card game with no stakes. The random number generator in a browser toolbox sits in this camp and should; predicting a dice result buys nobody anything.
Where nothing else will do
Password reset links. Session identifiers. API keys and one-time codes. CSRF tokens. Anything tied to an account boundary a stranger can attack. These need a CSPRNG, source-backed: crypto.getRandomValues or crypto.randomUUID in browsers, random_bytes in PHP, the secrets module in Python, crypto_rng in Go. A password generator used for anything real deserves this class of randomness too, since a guessable password is a guessable password however long.
The one-question habit
One question separates the two worlds: can anyone gain anything by predicting this value? For a dice roll, no. For a reset link, an attacker gains an account, and the four-billion-seed generator loses. Ask it at design time, when the fix is a one-line API swap, instead of in an incident report.