🍋
Menu
Best Practice Beginner 1 min read 233 words

Random Number Generation Best Practices

Understand the differences between pseudo-random and cryptographic random number generation for various use cases.

Random Number Generation

Not all random numbers are created equal. The distinction between pseudo-random number generators (PRNGs) and cryptographically secure random number generators (CSPRNGs) matters enormously depending on your use case.

Pseudo-Random vs Cryptographic Random

PRNGs like Mersenne Twister produce statistically uniform distributions that are perfectly adequate for simulations, games, and sampling. However, given enough output, an attacker can predict future values. CSPRNGs (like those provided by the Web Crypto API or /dev/urandom) use entropy from hardware events, making their output unpredictable even to someone who has seen billions of previous values.

Choosing the Right Generator

Use CSPRNGs for security-sensitive operations: generating passwords, API keys, session tokens, encryption keys, nonces, and salts. Use PRNGs for non-security applications: shuffling playlists, Monte Carlo simulations, procedural content generation, and A/B test bucketing. Never use Math.random() for anything security-related.

Common Pitfalls

Seeding a PRNG with the current timestamp gives only ~31 bits of entropy, making it trivially predictable. Modulo bias when constraining random numbers to a range produces non-uniform distributions — use rejection sampling instead. Generating random strings by concatenating random characters can produce unexpectedly short strings if the alphabet contains problematic characters.

Browser-Based Generation

The Web Crypto API (crypto.getRandomValues()) provides CSPRNG access in browsers without any external dependencies. For generating random UUIDs, use crypto.randomUUID() which is supported in all modern browsers. These APIs work entirely client-side with no server communication required.

相关工具

相关格式

相关指南