This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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