Skip to main content

Free 30-min security demo  — We'll scan your real code and show live findings, no commitment Book Now

Offensive360
Academy Insecure Randomness
Intermediate · 15 min

Insecure Randomness

Learn why Math.random() and rand() are predictable for security tokens and how to use cryptographic randomness.

1 Predictable Pseudo-Random Generators

Standard random number generators (Math.random, rand(), random.random) are designed for statistical randomness — not unpredictability. They use deterministic algorithms seeded from predictable values like the current time, making security-sensitive output guessable.

Vulnerable examples:

// JavaScript — Math.random() is NOT cryptographically secure
const token = Math.random().toString(36).substring(2);  // Predictable!
// PHP — rand() or mt_rand() are predictable
$token = md5(rand());  // Very predictable with known seed!
# Python — random module is predictable (Mersenne Twister)
import random
token = random.randint(0, 10**16)  # Guessable after observing outputs

Impact: Predictable tokens enable attackers to guess password reset links, CSRF tokens, session IDs, or API keys generated with insecure randomness. An attacker who can observe any output from the PRNG can predict future and past values.

2 Cryptographically Secure Randomness

Cryptographically secure pseudo-random number generators (CSPRNG) draw entropy from the operating system, making their output unpredictable even with knowledge of previous values.

Python — secrets module (recommended):

import secrets

# URL-safe token (256 bits) — for session IDs, API keys, reset tokens
token = secrets.token_urlsafe(32)

# Hex token
token = secrets.token_hex(32)

# Random integer in range
n = secrets.randbelow(1000000)

Node.js — crypto module:

const crypto = require("crypto");

// Buffer of random bytes
const token = crypto.randomBytes(32).toString("hex");

// URL-safe base64
const token = crypto.randomBytes(32).toString("base64url");

// In browser
const array = new Uint8Array(32);
crypto.getRandomValues(array);

Defense checklist:

  • Use secrets (Python), crypto.randomBytes (Node), SecureRandom (Java), openssl_random_pseudo_bytes (PHP)
  • Never use Math.random, rand(), or random.random for security tokens
  • Generate at least 128 bits (16 bytes) of randomness for tokens
  • Do not seed CSPRNG manually — use the OS entropy source

Knowledge Check

0/3 correct
Q1

Why is Math.random() unsuitable for generating security tokens?

Q2

Which Python module should be used for generating secure session tokens?

Q3

What is the minimum recommended number of bits of entropy for a session token?

Code Exercise

Use Cryptographic Randomness

The API key generation uses Python's random module, which is predictable. Replace it with the secrets module for cryptographically secure tokens.

python