๐ฒ Random String Generation: True Random vs Pseudo-Random
From fundamentals to practice โ understanding what cryptographically secure randomness really means
Why Do You Need "True" Randomness?
Writing a random string generator is easy โ but writing a secure one isn't as simple as calling Math.random(). If the random strings you generate are for password reset tokens, verification codes, or API keys โ and an attacker can predict your "random" output โ they've just been handed the keys to your system.
Math.random() is a "looks random" pseudo-random number generator (PRNG); crypto.getRandomValues() is a cryptographically secure random number generator (CSPRNG). The former is fast but predictable; the latter is slower but impossible to predict.
Math.random(): Why It's Not Secure Enough
How It Works
Math.random() uses a pseudo-random number generator (typically the xorshift128+ algorithm). It starts from an initial seed and continuously generates the next number through a mathematical formula. Given the same seed, you get the exact same sequence every time.
Three Fatal Weaknesses
- Predictability: If an attacker guesses the seed (e.g., the current timestamp), they can reproduce the entire random sequence
- State recovery: Observing a few consecutive outputs allows reconstructing the internal state and predicting future values
- Wrong design goals: V8's
Math.random()optimizes for speed and uniform distribution โ not security
// โ Never use Math.random() for security tokens!
function unsafeToken(len) {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let result = '';
for (let i = 0; i < len; i++) {
result += chars[Math.floor(Math.random() * chars.length)];
}
return result;
}
crypto.getRandomValues(): Cryptographically Secure
How It Works
crypto.getRandomValues() is the CSPRNG provided by the Web Crypto API. It draws from the operating system's true entropy sources โ mouse movements, keyboard timing, disk interrupts, network packet arrival times, and other hardware-level random events that are fundamentally unpredictable.
Why It's Secure
- Real entropy: Not computed from a formula โ collected from physical-world randomness
- Not reversible: Observing outputs doesn't let you reconstruct internal state or predict future values
- No seeding: There is no "seed" concept โ outputs cannot be reproduced
- Browser native: Available in all modern browsers with zero dependencies
// โ
Use crypto.getRandomValues() for secure tokens
function safeToken(len) {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const arr = new Uint32Array(len);
crypto.getRandomValues(arr);
let result = '';
for (let i = 0; i < len; i++) {
result += chars[arr[i] % chars.length];
}
return result;
}
| Property | Math.random() | crypto.getRandomValues() |
|---|---|---|
| Type | PRNG (pseudo-random) | CSPRNG (cryptographic) |
| Predictable? | Yes | No |
| Entropy source | Math formula + seed | OS hardware entropy |
| Speed | Extremely fast | Fast (entropy-pool limited) |
| Use cases | Games, animations, A/B tests | Passwords, tokens, crypto keys |
| Thread-safe | Yes | Yes |
When Do You Need Cryptographic Randomness?
- ๐ Generating API Keys / Access Tokens: Using Math.random() is handing the keys to an attacker
- ๐ง Password reset links: Predictable tokens = arbitrary account takeover
- ๐ซ Coupon / invite codes: If the pattern is guessable, your promo budget disappears
- ๐ฎ In-game "random" drops (not critical): Math.random() is perfectly fine
- ๐ Unique ID generation: UUID v4 already uses crypto under the hood
The Modulo Bias Problem
Even with crypto.getRandomValues(), using arr[i] % charset.length to pick a character technically introduces modulo bias. Since Uint32 ranges from 0 to 4,294,967,295, if the character set length doesn't evenly divide this range, some characters appear slightly more often.
In practice: When the character set length is much smaller than 2ยณยฒ, the bias is negligible (< 0.0000001%) and has no practical impact for almost all applications. For extreme uniformity requirements, rejection sampling is an option โ but for everyday use, modulo is more than sufficient.
๐ Generate a secure random string now
Configurable length, uppercase/lowercase/digits/special chars, uses crypto.getRandomValues
๐ฒ Open Random String GeneratorFAQ
Q: Can crypto.getRandomValues run out of randomness?
Operating systems maintain an entropy pool, continuously collecting randomness from hardware events. Normal applications will virtually never deplete it. In browsers, a single call generates up to 65,536 bytes โ more than enough. For large quantities, make multiple calls.
Q: Does Node.js have crypto.getRandomValues?
Yes! Node.js's crypto module provides both crypto.randomBytes() (the traditional API) and crypto.getRandomValues() (the Web-compatible API). Both use the OS's CSPRNG and are fully secure.
Q: Is Math.random() really that easy to crack?
For V8's xorshift128+ implementation, an attacker who observes roughly 3-4 consecutive Math.random() outputs (as 64-bit floats) can recover the internal state using a Z3 solver. Public proof-of-concept attack code has been available since 2018.