๐ŸŽฒ 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.

Key distinction: 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

// โŒ 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

// โœ… 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;
}
PropertyMath.random()crypto.getRandomValues()
TypePRNG (pseudo-random)CSPRNG (cryptographic)
Predictable?YesNo
Entropy sourceMath formula + seedOS hardware entropy
SpeedExtremely fastFast (entropy-pool limited)
Use casesGames, animations, A/B testsPasswords, tokens, crypto keys
Thread-safeYesYes

When Do You Need Cryptographic Randomness?

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 Generator

FAQ

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.