InterviewHubPRO
Section Overview
Q10

Question 10 of 50

Part 1: Candid Security Experience, Threat Modeling & Fundamentals (1 - 10)

20%
Web Security & OWASP (50 Qs)•Part 1: Candid Security Experience, Threat Modeling & Fundamentals (1 - 10)

Cryptographic Pseudo-Random Number Generators (CSPRNG): Math.random() vs. crypto.getRandomValues().

Predictable Entropy vs. Cryptographic Randomness

Generating security tokens, session identifiers, password reset tokens, or API keys using standard pseudo-random number generators (PRNG) introduces critical vulnerabilities.

less
Standard PRNG (Math.random()):
[ Seed / Linear Congruential Generator ] ---> Predictable mathematical sequence!
Attacker observing 2-3 tokens can deduce the internal state and predict future tokens!

Cryptographic PRNG (CSPRNG):
[ Hardware Entropy: CPU Thermal Noise, Interrupt Jitter, /dev/urandom ]
                       |
                       v
[ High-Entropy Cryptographic Stream (CSPRNG) ] ---> Mathematically Unpredictable

Vulnerability Example & Secure Replacement

typescript
// VULNERABLE: Math.random() is NOT cryptographically secure!
function generateSessionTokenUnsafe(): string {
  return Math.random().toString(36).substring(2); // DANGEROUS!
}

// SECURE: Node.js Crypto / Web Crypto API (CSPRNG)
import crypto from 'crypto';

function generateSecureToken(bytes: number = 32): string {
  return crypto.randomBytes(bytes).toString('hex'); // 256 bits of true entropy
}

// Browser Web Crypto API
function generateSecureBrowserToken(): string {
  const array = new Uint8Array(32);
  window.crypto.getRandomValues(array);
  return Array.from(array, byte => byte.toString(16).padStart(2, '0')).join('');
}