Non-cryptographic random number generator
Using Math.random(), Python's random module, java.util.Random, Go's math/rand or similar for keys, tokens, nonces or passwords.
Why it's at risk
These generators are designed for simulations, not secrecy: their output can often be predicted after observing a few values, which lets attackers guess session tokens, reset links or keys. This is a classical bug that no quantum-safe algorithm fixes. Use the platform's cryptographically secure generator (crypto.randomBytes / crypto.getRandomValues, secrets, SecureRandom, crypto/rand).
- Used for
- Randomness
- Family
- Random number generation
- Standards
- NIST SP 800-90A Rev. 1
Migration guides
Concrete code changes to move off Non-cryptographic random number generator. Pick your stack.
node:crypto / Web Crypto · javascriptJavaScript: replace Math.random() for tokens, IDs and keys with a CSPRNGProduction-ready
Why
Math.random() is designed to be fast, not unpredictable. V8's generator (xorshift128+) can be reconstructed from a handful of outputs, so tokens built from it (password-reset links, session IDs, API keys, invite codes, nonces) can be predicted. Use a cryptographically secure random number generator (CSPRNG). Quantum computers are irrelevant here; this is a classical bug.
Before
const token = Math.random().toString(36).slice(2);
const otp = Math.floor(Math.random() * 1_000_000);After
import { randomBytes, randomInt, randomUUID } from 'node:crypto';
const token = randomBytes(32).toString('base64url'); // 256-bit token
const otp = randomInt(0, 1_000_000).toString().padStart(6, '0'); // unbiased
const id = randomUUID(); // v4 UUID from the CSPRNG
// Browsers, Deno, Bun, workers and Node 19+ (global Web Crypto):
const bytes = crypto.getRandomValues(new Uint8Array(32));
const uuid = crypto.randomUUID();Gotchas
- Avoid modulo bias:
bytes[0] % 10is biased; userandomIntor rejection sampling. - Libraries: check ID/token packages (
nanoidis CSPRNG-backed; some older "shortid"-style packages are not). - Math.random() is fine for games, jitter, sampling and UI effects; the scanner may flag those, so mark them as accepted.
- Store only hashes of long-lived tokens (e.g. SHA-256 of an API key) so a database leak doesn't leak usable tokens.
Verify
npx -y pqe-cli scan . reports remaining Math.random() uses in security-looking contexts; review each.
secrets (stdlib) · pythonPython: use secrets, not random, for tokens, passwords and keysProduction-ready
Why
Python's random module is a Mersenne Twister: after observing 624 32-bit outputs, an attacker can predict all future ones. The secrets module (Python 3.6+) uses the operating system's CSPRNG and is the right tool for anything security-related.
Before
import random, string
token = "".join(random.choice(string.ascii_letters + string.digits) for _ in range(20))
otp = random.randint(0, 999999)After
import secrets, string
token = secrets.token_urlsafe(32) # 32 random bytes, URL-safe text
key = secrets.token_bytes(32) # e.g. an AES-256 key
otp = f"{secrets.randbelow(1_000_000):06d}"
alphabet = string.ascii_letters + string.digits
password = "".join(secrets.choice(alphabet) for _ in range(20))
ok = secrets.compare_digest(a, b) # constant-time comparisonGotchas
random.SystemRandom()is also OS-backed, butsecretsis clearer.- NumPy's
np.randomis not cryptographic either. uuid.uuid4()usesos.urandomand is fine for unguessable IDs.randomis fine for simulations, sampling and tests; mark those as accepted in scan results.
Verify
npx -y pqe-cli scan . and grep for import random in security-relevant modules.
crypto/rand · goGo: use crypto/rand, not math/rand, for secretsProduction-ready
Why
math/rand and math/rand/v2 are not designed to be unpredictable (math/rand/v2's ChaCha8 source is better, but the package documentation still says not to use it for security-sensitive work). Keys, tokens and nonces must come from crypto/rand.
Before
import "math/rand"
b := make([]byte, 32)
rand.Read(b) // deprecated and not secure
token := fmt.Sprintf("%x", b)After
import (
"crypto/rand"
"encoding/base64"
"math/big"
)
token := rand.Text() // Go 1.24+: 26-character base32 string, 128 bits of entropy
b := make([]byte, 32)
_, _ = rand.Read(b) // since Go 1.24 crypto/rand.Read never returns an error (it crashes the program on failure)
key := b
n, err := rand.Int(rand.Reader, big.NewInt(1_000_000)) // unbiased number in [0, 1e6)
_ = base64.RawURLEncoding.EncodeToString(key)Gotchas
- Import aliases: files importing both packages often alias one; make sure security code uses
crypto/rand. math/randis fine for jitter, shuffling test data and simulations.
Verify
go vet won't catch this; npx -y pqe-cli scan . flags math/rand in security-looking code.
java.security.SecureRandom · javaJava/Kotlin: use SecureRandom, not java.util.Random or Math.random(), for secretsProduction-ready
Why
java.util.Random is a 48-bit linear congruential generator: two outputs are enough to recover its state and predict everything after. Math.random() and ThreadLocalRandom are not cryptographic either. Use java.security.SecureRandom.
Before
Random r = new Random();
String token = Long.toHexString(r.nextLong());After
import java.security.SecureRandom;
import java.util.Base64;
SecureRandom rng = new SecureRandom(); // reuse one instance; thread-safe
byte[] bytes = new byte[32];
rng.nextBytes(bytes);
String token = Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
int otp = rng.nextInt(1_000_000); // unbiased boundKotlin: java.security.SecureRandom() the same way; kotlin.random.Random is not cryptographic.
Gotchas
- Don't seed SecureRandom with a constant; with some algorithms an explicit seed replaces the OS entropy.
SecureRandom.getInstanceStrong()can block on some Linux setups; the default constructor is fine for tokens and keys.UUID.randomUUID()uses SecureRandom and is fine for unguessable IDs.
Verify
npx -y pqe-cli scan . flags java.util.Random / Math.random() in security-looking code.