Skip to content

Instantly share code, notes, and snippets.

@dchest
Created April 11, 2014 10:50
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 dchest/10457887 to your computer and use it in GitHub Desktop.
Save dchest/10457887 to your computer and use it in GitHub Desktop.
function getRandomBytes(length) {
var bytes = new Uint8Array(length);
window.crypto.getRandomValues(bytes);
return bytes;
}
function generatePassword(length) {
// To avoid modulo bias, alphabet length must conform to 256 % length == 0, e.g. 64.
var alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_@'.split('');
var bytes = getRandomBytes(length);
var result = "", i;
for (i = 0; i < length; i++) {
result += alphabet[bytes[i] % alphabet.length];
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment