Difficulty: Advanced
What is a CSPRNG, why is Math.random() unsafe for security tokens, and which APIs should you use instead?
A CSPRNG (cryptographically secure pseudo-random number generator) produces output that an attacker cannot predict, even after seeing a large amount of previous output. General-purpose generators like JavaScript's Math.random(), Java's java.util.Random or Python's random module are fast and statistically uniform but predictable: their internal state can be recovered from a few outputs. Any value that protects something, such as session IDs, password reset tokens, OTPs, API keys or CSRF tokens, must come from a CSPRNG.
Non-cryptographic PRNGs are designed for simulations and games. They have small internal states and simple update functions. V8's Math.random() uses xorshift128+, and researchers have shown its state can be reconstructed from a handful of outputs, after which every future (and past) value is known. Python's random uses Mersenne Twister, whose state can be rebuilt from 624 consecutive 32-bit outputs.
If your password reset link uses Math.random().toString(36), an attacker who requests a few resets for their own account can predict the token generated for someone else's.
getrandom() and /dev/urandom on Linux, or BCryptGenRandom on Windows. On modern Linux, /dev/urandom is the right choice; the old advice to prefer /dev/random is outdated.| Language | Insecure | Secure |
|---|---|---|
| Browser JS | Math.random() | crypto.getRandomValues(), crypto.randomUUID() |
| Node.js | Math.random() | crypto.randomBytes(), crypto.randomInt(), crypto.randomUUID() |
| Python | random | secrets.token_urlsafe(), secrets.randbelow() |
| Java | java.util.Random | java.security.SecureRandom |
| Go | math/rand | crypto/rand |
randomBytes(1)[0] % 10 makes some digits more likely. Use crypto.randomInt(0, 10) or rejection sampling.sha256(Date.now()) looks random but has almost no entropy.For a 6-digit OTP the CSPRNG prevents prediction, but the space is still only a million values, so you also need short expiry and attempt limits.
| Math.random / Mersenne Twister | CSPRNG (crypto, secrets) | |
|---|---|---|
| Seed source | Small internal seed | OS entropy pool |
| Predictable from outputs | Yes, state is recoverable | No |
| Speed | Very fast | Fast enough for tokens |
| Use for | Games, simulations, shuffling UI | Tokens, keys, OTPs, nonces |
import crypto from "node:crypto";
// 32 bytes = 256 bits, URL-safe for reset links
const resetToken = crypto.randomBytes(32).toString("base64url");
// Store only the hash in the database
const tokenHash = crypto.createHash("sha256").update(resetToken).digest("hex");
// Unbiased 6-digit OTP
const otp = crypto.randomInt(0, 1_000_000).toString().padStart(6, "0");
// Random UUIDv4 from the CSPRNG
const id = crypto.randomUUID();
console.log({ resetToken, tokenHash, otp, id });
randomBytes and randomInt use the OS CSPRNG, and randomInt avoids modulo bias. Only the hash of the reset token is stored.
import secrets
api_key = "sk_live_" + secrets.token_urlsafe(32) # 256 bits
otp = f"{secrets.randbelow(10**6):06d}" # unbiased 6 digits
# Constant-time comparison when checking a submitted token
def check(submitted: str, expected: str) -> bool:
return secrets.compare_digest(submitted, expected)
The secrets module exists specifically for security tokens; the random module should never be used for them.
CSPRNG, Entropy, Math.random, crypto.getRandomValues, Token Generation, Modulo Bias