Skip to content

Instantly share code, notes, and snippets.

@jhsuZerion
Created June 13, 2018 13:59
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 jhsuZerion/3ba4c43178ba20469748cc67a91e9484 to your computer and use it in GitHub Desktop.
Save jhsuZerion/3ba4c43178ba20469748cc67a91e9484 to your computer and use it in GitHub Desktop.
JavaScript function to generate randomized passwords
/**
* Generates a random password for a given length and complexity
* @param {int} len number of characters in the password
* @param {boolean} upper toggle to include uppercase letters
* @param {boolean} number toggle to include numeric digits
* @param {boolean} special toggle to include special characters
* @param {boolean} space toggle to include non-breaking space
* @return {string} password including minimum 1 character of each complexity
*/
function genPassword(len,upper,number,special,space) {
var lower_chars = "abcdefghijklmnopqrstuvwxyz";
var upper_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var numbers = "1234567890";
var special_chars = "!@#$%^&*";
var password = lower_chars[Math.floor(Math.random() * lower_chars.length)];;
var complexity = [1,0,0,0,0];
if(upper === true) {
password += upper_chars[Math.floor(Math.random() * upper_chars.length)];
complexity[1] = 1;
}
if(number === true) {
password += numbers[Math.floor(Math.random() * numbers.length)];
complexity[2] = 1;
}
if(special === true) {
password += special_chars[Math.floor(Math.random() * special_chars.length)];
complexity[3] = 1;
}
if(space === true) {
password += " ";
complexity[4] = 1;
}
for(var i=password.length; i<len; i++) {
do {
var char_type = Math.floor(Math.random() * 5);
} while(complexity[char_type] != 1);
switch(char_type) {
case 0:
password += lower_chars[Math.floor(Math.random() * lower_chars.length)];
break;
case 1:
password += upper_chars[Math.floor(Math.random() * upper_chars.length)];
break;
case 2:
password += numbers[Math.floor(Math.random() * numbers.length)];
break;
case 3:
password += special_chars[Math.floor(Math.random() * special_chars.length)];
break;
case 4:
password += " ";
break;
}
}
function scramble(a){a=a.split("");for(var b=a.length-1;0<b;b--){var c=Math.floor(Math.random()*(b+1));d=a[b];a[b]=a[c];a[c]=d}return a.join("")}
return scramble(password);
}
//console.log(genPassword(25,true,false,true,false));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment