Menu

Why Math.random() Is Unsafe for Password Generation (And What to Use Instead)
📰

Why Math.random() Is Unsafe for Password Generation (And What to Use Instead)

DEV Community: security·Ian Bishop·about 1 hour ago
#MGju2P2z
#devtosecurity#devto#dev#password#random
Reading 0:00
15s threshold

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 .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.