Created
March 2, 2014 19:46
-
-
Save j0lvera/9312705 to your computer and use it in GitHub Desktop.
pwg.js a strong password generator
This file contains hidden or 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
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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This has an ever-so-slight bias in the all characters case towards the first 16 letters since
Math.pow(2, 32) % random.length
is16
, and towards the first 48 letters in the onlyLetters case.