JavaScript makes it remarkably easy to generate random-looking strings. But when those strings are intended to protect accounts, API credentials, or sensitive systems, the source of randomness matters.
A password can look complicated and still be vulnerable if the underlying random number generator is predictable.
Let's examine why Math.random() is unsuitable for password generation and build a more secure alternative using the browser's native Web Crypto API.
The problem with Math.random()
A common password generator implementation looks something like this:
const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" ;
function generatePassword ( length = 16 ) { let password = "" ;
for ( let i = 0 ; i < length ; i ++ ) { const index = Math . floor ( Math . random ( ) * characters .…