Skip to main content

Insecure randomness: Math.random, random and tokens that can be guessed

A password reset link, an API key, a session id and an invite code are all passwords that nobody types. Their only protection is that nobody can guess them. Generate one with a predictable random number generator and that protection is gone, even though every token looks random to the eye.

The bug is easy to write because every language has two kinds of random. One is fast and designed for simulations, games and shuffling. The other reads from the operating system's cryptographic generator. This post covers which is which in each language, how much randomness a token needs, and the mistakes that weaken a good generator: truncation, modulo bias and treating a UUID as a secret.

Why the ordinary generator is not enough

General-purpose generators are deterministic: the next output follows from an internal state. The documentation for each is blunt about what that means.

  • MDN on Math.random(): it does not provide cryptographically secure random numbers, so do not use it for anything related to security.
  • Python random: the Mersenne Twister is "completely unsuitable for cryptographic purposes", and the module should not be used for security.
  • Go math/rand/v2: its outputs "might be easily predictable regardless of how it's seeded".
  • PHP mt_rand: must not be used where values need to be unguessable.
  • Java java.util.Random: instances are not cryptographically secure; use SecureRandom.

The practical risk is that an attacker who can see some outputs, for example their own reset tokens or invite codes, can recover the generator's state and predict the tokens issued to other users. Seeding with the current time makes it worse, because the seed itself can be guessed.

The secure generator in each language

Language Do not use for secrets Use
JavaScript (Node) Math.random() crypto.randomBytes(32), crypto.randomUUID(), crypto.randomInt()
JavaScript (browser) Math.random() crypto.getRandomValues(), crypto.randomUUID()
Python random.* secrets.token_urlsafe(32), secrets.token_bytes(), secrets.choice()
Go math/rand, math/rand/v2 crypto/rand.Read, crypto/rand.Text() (Go 1.24+)
Java Random, Math.random(), ThreadLocalRandom SecureRandom
PHP rand(), mt_rand(), uniqid() random_bytes(), random_int()

In code:

// Node.js
const { randomBytes } = require("node:crypto");

const weak = Math.random().toString(36).slice(2);   // predictable from earlier outputs
const token = randomBytes(32).toString("base64url"); // 256 bits from the OS CSPRNG
# Python
import secrets

token = secrets.token_urlsafe(32)  # 32 random bytes, URL-safe text
// Go
import "crypto/rand"

func newToken() string {
	return rand.Text() // Go 1.24+: at least 128 bits, base32
}
// Java
import java.security.SecureRandom;
import java.util.Base64;

final class Tokens {
    private static final SecureRandom RNG = new SecureRandom();

    static String newToken() {
        byte[] bytes = new byte[32];
        RNG.nextBytes(bytes);
        return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
    }
}
// PHP
$token = bin2hex(random_bytes(32));

How much randomness a token needs

The Python secrets documentation says that, as of 2015, 32 bytes (256 bits) is believed sufficient for typical use. Go's rand.Text() gives at least 128 bits. A useful rule: 128 bits as a floor for anything that grants access on its own (reset links, API keys, session ids, magic links), 256 bits when you have no reason to go shorter.

Short codes that humans type, such as a six-digit email or SMS code, cannot reach that. Their safety comes from the surrounding controls: a short expiry, a small number of attempts per code and per account, and invalidation after use. A six-digit code with unlimited attempts is a brute-force exercise, however good the generator.

Mistake 1: truncating a good value

inviteCode := uuid.NewString()[0:8] // 8 hex characters: 32 bits

A random UUID carries 122 random bits. The first eight hex characters keep 32 of them, which an attacker can enumerate. If you need a short code, generate it at the length you need from the CSPRNG and add the rate limits above; do not cut down a longer value and assume it stays strong.

Mistake 2: modulo bias

Mapping random bytes onto an alphabet with % is biased whenever the alphabet length does not divide 256. With 36 characters, the first 4 characters come up more often than the rest:

const ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789";

// Biased: 256 % 36 = 4, so "a" to "d" are more likely
const biased = [...randomBytes(16)].map((b) => ALPHABET[b % ALPHABET.length]).join("");

// Unbiased: crypto.randomInt avoids modulo bias
const { randomInt } = require("node:crypto");
const code = Array.from({ length: 16 }, () => ALPHABET[randomInt(ALPHABET.length)]).join("");

The Node.js docs state that crypto.randomInt avoids modulo bias. In Python, secrets.choice does the same job.

Mistake 3: UUIDs as secrets

RFC 9562, which obsoleted RFC 4122 in May 2024, says in its security considerations that implementations "SHOULD NOT assume that UUIDs are hard to guess" and that UUIDs "MUST NOT be used as security capabilities". The versions differ a lot:

Version Contents As a secret
v1 60-bit timestamp, clock sequence, 48-bit node (often a MAC address) No: largely predictable
v4 122 random bits Depends entirely on the generator behind it
v7 48-bit millisecond timestamp, 74 random bits No: the time is exposed and the random part is shorter

A v4 UUID from a CSPRNG is hard to guess (Node documents that crypto.randomUUID() uses a cryptographic generator), but a hand-rolled v4 built on Math.random() is not, and nothing in the string tells you which one you have. Use UUIDs as identifiers. Generate tokens with the token functions above, so the intent is obvious to the next reader.

Store and compare tokens safely

Treat a token like a password once it is issued. Store a hash of it (a fast hash such as SHA-256 is fine for 128 bits or more of randomness), so a database leak does not hand out working reset links. Give it an expiry. Delete it after use. Compare it with a constant-time function, as covered in timing-safe comparison.

Finding weak randomness with Vulkro

Vulkro Core reports non-cryptographic generators when the value is used as a security token, plus the mistakes that weaken a good generator:

vulkro scan . --format json > findings.json
vulkro explain truncated-random-token
vulkro scan . --format cbom > cbom.json
Rule What it flags
insecure-rng-call Math.random(), random.* and similar next to a credential-shaped name
py-random-for-security-token, go-insecure-rng-for-token, java-insecure-random-security-context, php-insecure-randomness-security-value Language-specific weak generators feeding a token, key, secret or nonce
truncated-random-token A random or UUID value sliced to a short token
weak-random-uuid A UUID built from Math.random() reused as a reset, session, invite or verification token
pseudo-random-bytes-for-security-value Node's crypto.pseudoRandomBytes() used for a security value

The rules fire only when the value is plausibly a security token, judged by the variable, function or charset name, so Math.random() in an animation or a shuffle is left alone. The cbom output lists insecure RNG use among the cryptographic assets with file and line, which some compliance reviews ask for.

FAQ

Is Math.random secure for tokens?

No. MDN states that Math.random() does not provide cryptographically secure random numbers. In Node use crypto.randomBytes or crypto.randomUUID, and in browsers use crypto.getRandomValues.

What should I use instead of random in Python?

The secrets module. secrets.token_urlsafe(32) gives a URL-safe token with 32 random bytes, and secrets.choice picks from a sequence without bias. The random module is for modelling and simulation.

Can a UUID be used as a password reset token?

It is better not to. RFC 9562 says UUIDs should not be assumed hard to guess and must not be used as security capabilities. v1 and v7 expose a timestamp, and a v4 is only as strong as its generator. Use a dedicated token function.

See the developers in VS Code use case and the output formats reference, or start a 14-day trial. Related: the sign-in that never checks the signature and timing-safe comparison.