🍋
Menu
Best Practice Beginner 1 min read 241 words

Secure Random Number Generation: When Math.random() Isn't Enough

Math.random() is fine for shuffling a playlist but dangerous for passwords, tokens, and cryptographic applications. Learn when and how to use cryptographically secure random generators.

The Problem with Math.random()

JavaScript's Math.random() and similar standard library random functions use pseudorandom number generators (PRNGs). Given the seed, the entire sequence is predictable. This is fine for games, simulations, and UI effects, but disastrous for security-sensitive applications.

When You Need CSPRNG

Use a Cryptographically Secure Pseudo-Random Number Generator (CSPRNG) for: password generation, session tokens, API keys, encryption keys, CSRF tokens, one-time passwords, and any value an attacker could benefit from predicting.

Platform-Specific APIs

In browsers, use crypto.getRandomValues() which draws from the operating system's entropy pool. In Node.js, use crypto.randomBytes() or crypto.randomUUID(). In Python, use secrets.token_hex(), secrets.token_urlsafe(), or secrets.choice(). Never implement your own random number generator for security purposes.

Common Mistakes

Using Math.random() for token generation — an attacker can predict subsequent tokens after observing enough output. Seeding a PRNG with a predictable value (timestamp, PID) — the attacker can reproduce the seed. Reducing entropy by truncating random output — a 128-bit random value truncated to 32 bits has only 32 bits of security. Using modulo to restrict range — random % n introduces bias when n doesn't divide evenly into the PRNG's output range.

Entropy Sources

Operating systems gather entropy from hardware events: disk I/O timing, network packet timing, mouse movements, keyboard input. /dev/urandom (Linux) and CryptGenRandom (Windows) maintain entropy pools that CSPRNG functions draw from. On headless servers with minimal I/O, consider hardware random number generators (Intel RDRAND, ARM RNDR) for additional entropy.

Ilgili Araclar

Ilgili Formatlar

Ilgili Rehberler