CSPRNG

Difficulty: Advanced

Question

What is a CSPRNG, why is Math.random() unsafe for security tokens, and which APIs should you use instead?

Answer

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.

Why "random looking" is not enough

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.

What makes a CSPRNG different

  • Seeded from real entropy collected by the operating system (hardware events, interrupt timing, CPU RNG instructions).
  • Unpredictability: knowing past outputs does not help predict the next one.
  • Backtracking resistance: compromising the current state does not reveal earlier outputs.
  • Backed by OS sources such as 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.

Which API to use

LanguageInsecureSecure
Browser JSMath.random()crypto.getRandomValues(), crypto.randomUUID()
Node.jsMath.random()crypto.randomBytes(), crypto.randomInt(), crypto.randomUUID()
Pythonrandomsecrets.token_urlsafe(), secrets.randbelow()
Javajava.util.Randomjava.security.SecureRandom
Gomath/randcrypto/rand

Common mistakes

  • Too few bits: use at least 128 bits of randomness for tokens (16 random bytes). A UUIDv4 has 122 random bits, which is acceptable when generated by a CSPRNG, but do not use UUIDv1 or v7 as secrets because they contain timestamps.
  • Modulo bias: randomBytes(1)[0] % 10 makes some digits more likely. Use crypto.randomInt(0, 10) or rejection sampling.
  • Seeding with time or PID: a manually seeded generator collapses to a few thousand possible states.
  • Hashing a weak value: sha256(Date.now()) looks random but has almost no entropy.
  • Storing tokens in plaintext: store a hash of reset tokens and API keys, so a database leak does not hand out live tokens.

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.

PRNG vs CSPRNG. Both look random; only one is safe when an attacker is watching.
Math.random / Mersenne TwisterCSPRNG (crypto, secrets)
Seed sourceSmall internal seedOS entropy pool
Predictable from outputsYes, state is recoverableNo
SpeedVery fastFast enough for tokens
Use forGames, simulations, shuffling UITokens, keys, OTPs, nonces

Code examples

Generating secure tokens in Node.js

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.

Python secrets module

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.

Key points

  • Math.random, java.util.Random and Python random are predictable; never use them for secrets.
  • Use crypto.getRandomValues / randomBytes / randomInt, secrets, SecureRandom or crypto/rand.
  • Aim for at least 128 bits of entropy in tokens.
  • Avoid modulo bias; use randomInt or randbelow for ranges.
  • Store hashes of reset tokens and API keys, not the raw values.

Common follow-up questions

  • How would an attacker exploit a password reset token built with Math.random()?
  • What is modulo bias and how do you avoid it?
  • Is a UUID safe to use as a session ID?
  • What is the difference between /dev/random and /dev/urandom on Linux today?

Interview tips

  • Explain why predictability matters with a concrete reset-token attack.
  • Name the right API in the language you are interviewing in.
  • Mention entropy size and storing hashes of tokens to show end-to-end thinking.

Concepts covered

CSPRNG, Entropy, Math.random, crypto.getRandomValues, Token Generation, Modulo Bias

More Web Security (OWASP, JWT, XSS, CSRF) questions