Skip to content

Instantly share code, notes, and snippets.

@j0lvera
Created March 2, 2014 19:46
Show Gist options
  • Save j0lvera/9312705 to your computer and use it in GitHub Desktop.
Save j0lvera/9312705 to your computer and use it in GitHub Desktop.
pwg.js a strong password generator
function pwg(length, option) {
var pw = "",
arr = [],
isOpera = false,
chars = [
"abcdefghijklmnopqrstuvwxyz",
"1234567890",
"!@#$%&*()_+}{:?-=}[;/.,]",
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
],
random = chars.join(''),
onlyLetters = chars[0] + chars[3];
if (window.crypto && window.crypto.getRandomValues) {
arr = new Uint32Array(length);
window.crypto.getRandomValues(arr);
} else if (navigator.userAgent.indexOf('Opera') > -1) {
isOpera = true;
} else {
throw new Error("Your browser can't generate secure random numbers");
}
function randomNum(len, opt) {
var res = "", m = "";
opt === false ? m = onlyLetters : m = random;
for (var i = 0; i < len; i++) {
isOpera ? res += m[Math.floor(Math.random() * m.length)] : res += m[arr[i] % m.length];
}
return res;
}
return randomNum(length, option);
}
@mkropat
Copy link

mkropat commented Oct 26, 2017

This has an ever-so-slight bias in the all characters case towards the first 16 letters since Math.pow(2, 32) % random.length is 16, and towards the first 48 letters in the onlyLetters case.

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