Skip to content

Instantly share code, notes, and snippets.

@DavidWells
Created March 23, 2020 21:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save DavidWells/defd14cb196f766cbd86a077afb31615 to your computer and use it in GitHub Desktop.
Save DavidWells/defd14cb196f766cbd86a077afb31615 to your computer and use it in GitHub Desktop.
Generate random password
const CHARS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+-={}[]:;<>?/|\\';
function generatePassword(length = 12) {
let pass = '';
for (let i = length; i > 0; --i) pass += CHARS[Math.floor(Math.random() * CHARS.length)];
return pass
}
// Usage:
generatePassword(15)
// > "hBI!A31Hs}(oIv*"
@joonas-fi
Copy link

Don't mean to intrude, but I just wanted to chime in that the password security, when derived from Math.random(), is low:

Math.random() does not provide cryptographically secure random numbers. Do not use them for anything related to security. Use the Web Crypto API instead, and more precisely the window.crypto.getRandomValues() method.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment