DEV Community

Discussion on: Build a Password Generator API on Nodejs

Collapse
 
sqlrob profile image
Robert Myers

It really depends on what version of node you're using.

crypto.randomInt is safest, but only on a few versions.

Most portable is crypto.randomBytes, but there's some subtleties on using that you have to be careful of. When coercing that to your index, you must not use the modulo operator, since you'll bias the results. If something is too large, just toss it out. Probably the most efficient is to mask it down to the nearest set of all 1s and then toss out anything too large (i.e. for the numbers use & 0xf, then throw out anything over 9 and try again)

The shuffle probably isn't secure either, but I have trouble convincing myself it'll actually be a problem. They'll probably be somewhat easier to crack, but long enough passwords and it won't matter. The secure way is to make the password, and if it doesn't meet the qualifications, throw it out, or change some of the characters (picked at a cryptographicaly random position). One thing you learn from doing security enough though, if you have a hunch that something isn't secure, you're probably right.