Skip to content

Instantly share code, notes, and snippets.

@jkatz
Last active August 8, 2019 02:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jkatz/a66aa2a68e1c4100552bc9963622c6a4 to your computer and use it in GitHub Desktop.
Save jkatz/a66aa2a68e1c4100552bc9963622c6a4 to your computer and use it in GitHub Desktop.
const PASSWORD_CHARACTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
+ 'abcdefghijklmnopqrstuvwxyz'
+ '01234567890'
+ '!#$%&()*+,-./:;<=>?@[]^_`{|}~\/"\' ';
function generateRandomPassword(passwordLength=16) {
// if crypto not defined, bail
if (!window.crypto) {
throw new Error('The "crypto" library is not available');
}
// can't be larger than 1024 as not to exhaust the random number generator
if (length < 1 || length > 1024) {
throw new Error('Passwords must be between 1 and 1024 characters');
}
let randomValues = new Uint32Array(passwordLength),
password = "",
totalPasswordCharacters = PASSWORD_CHARACTERS.length;
window.crypto.getRandomValues(randomValues);
randomValues.forEach((val) => {
password += PASSWORD_CHARACTERS[val % (totalPasswordCharacters - 1)];
});
return password;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment