Skip to content

Instantly share code, notes, and snippets.

@quisido
Last active August 2, 2018 22:45
Show Gist options
  • Save quisido/b49b3245815ebff87ae8e4daa3b9946d to your computer and use it in GitHub Desktop.
Save quisido/b49b3245815ebff87ae8e4daa3b9946d to your computer and use it in GitHub Desktop.
Establishing a Secure Password Generator for Your User Base
// Valid characters.
var characters =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" +
"0123456789`~!@#$%^&*()_-+=[{]}|;:,.<>/?";
// password(X) will return a password of length X.
// password() will return a password of length 12.
var password = function(size) {
// Placeholder string, where our final password will end up.
var temp = "";
// If size is set, use it.
// If size is not set (or 0), default to a length of 12.
var len = size || 12;
// We will choose a random character this many times.
for (var x = 0; x < len; x++) {
// Generate a random number from 0 to 1 (think percentage).
var randomNumber = Math.random();
// Multiply by the number of characters in our list.
// The total length times a percentage will give us
// an exact location in our string of characters.
// 0% of 10 characters will be the 1st character.
// 50% of 10 characters will be the 5th character.
// 100% of 10 characters will be the 10th character.
var randomFloatingIndex = randomNumber * characters.length;
// Round this index down because indices are whole numbers that start at 0.
var randomIndex = Math.floor(randomFloatingIndex);
// Get the character at this random index.
var randomCharacter = characters.charAt(randomIndex);
// Append that character to our password-in-the-making.
temp += randomCharacter;
}
// Return our password-in-the-making now it is complete.
return temp;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment