Beyond Math.random(): Secure Password Generation in the Browser
Most developers reach for Math.random() for simple tasks, but for security, it is fundamentally flawed.
The Problem with PRNGs
Math.random() uses a Pseudo-Random Number Generator (PRNG) that is designed for speed, not security. Its outputs are predictable if you know the internal state.
Web Crypto API
The crypto.getRandomValues() method provides access to a cryptographically strong source of entropy. It fills a typed array with random values that are truly unpredictable, making it the only choice for generating passwords or encryption keys.
Practical Implementation
To generate a secure string, create a Uint32Array, fill it with random values, and map those values to a character set. This ensures uniform distribution and maximum resistance to brute force.