javascript password generator

Viewed 165239

What would be the best approach to creating a 8 character random password containing a-z, A-Z and 0-9?

Absolutely no security issues, this is merely for prototyping, I just want data that looks realistic.

I was thinking a for (0 to 7) Math.random to produce ASCII codes and convert them to characters. Do you have any other suggestions?

32 Answers

code to generate a password with a given length (default to 8) and have at least one upper case, one lower, one number and one symbol

(2 functions and one const variable called 'Allowed')

const Allowed = {
    Uppers: "QWERTYUIOPASDFGHJKLZXCVBNM",
    Lowers: "qwertyuiopasdfghjklzxcvbnm",
    Numbers: "1234567890",
    Symbols: "!@#$%^&*"
}

const getRandomCharFromString = (str) => str.charAt(Math.floor(Math.random() * str.length))
const generatePassword = (length = 8) => { // password will be @Param-length, default to 8, and have at least one upper, one lower, one number and one symbol
    let pwd = "";
    pwd += getRandomCharFromString(Allowed.Uppers); //pwd will have at least one upper
    pwd += getRandomCharFromString(Allowed.Lowers); //pwd will have at least one lower
    pwd += getRandomCharFromString(Allowed.Numbers); //pwd will have at least one number
    pwd += getRandomCharFromString(Allowed.Symbols);//pwd will have at least one symbolo
    for (let i = pwd.length; i < length; i++)
        pwd += getRandomCharFromString(Object.values(Allowed).join('')); //fill the rest of the pwd with random characters
    return pwd
}

I see much examples on this page are using Math.random. This method hasn't cryptographically strong random values so it's unsecure. Instead Math.random recomended use getRandomValues or your own alhorytm.

You can use passfather. This is a package that are using much cryptographically strong alhorytmes. I'm owner of this package so you can ask some question.

passfather

Here's my take (with Typescript) on this using the browser crypto API and enforcing a password which has at least:

  • 1 lower case letter
  • 1 upper case letter
  • 1 symbol
const LOWER_CASE_CHARS = 'abcdefghijklmnopqrstuvwxyz'.split('');
const UPPER_CASE_CHARS = LOWER_CASE_CHARS.map((x) => x.toUpperCase());
const SYMBOLS = '!£$%^&*()@~:;,./?{}=-_'.split('');
const LETTERS_MIX = [...LOWER_CASE_CHARS, ...UPPER_CASE_CHARS, ...SYMBOLS];
const CHARS_LENGTH = LETTERS_MIX.length;

function containsLowerCase(str: string): boolean {
  return LOWER_CASE_CHARS.some((x) => str.includes(x));
}

function containsUpperCase(str: string): boolean {
  return UPPER_CASE_CHARS.some((x) => str.includes(x));
}

function containsSymbol(str: string): boolean {
  return SYMBOLS.some((x) => str.includes(x));
}

function isValidPassword(password: string) {
  return containsLowerCase(password) && containsUpperCase(password) && containsSymbol(password);
}

export function generateStrongPassword(length: number = 16): string {
  const buff = new Uint8Array(length);

  let generatedPassword = '';

  do {
    window.crypto.getRandomValues(buff);
    generatedPassword = [...buff].map((x) => LETTERS_MIX[x % CHARS_LENGTH]).join('');
  } while (!isValidPassword(generatedPassword));

  return generatedPassword;
}

Stop the madness!

My pain point is that every Sign-Up tool allows a different set of special characters. Some might only allow these @#$%&* while others maybe don't allow * but do allow other things. Every password generator I've come across is binary when it comes to special characters. It allows you to either include them or not. So I wind up cycling through tons of options and scanning for outliers that don't meet the requirements until I find a password that works. The longer the password the more tedious this becomes. Finally, I have noticed that sometimes Sign-Up tools don't let you repeat the same character twice in a row but password generators don't seem to account for this. It's madness!

I made this for myself so I can just paste in the exact set of special characters that are allowed. I do not pretend this is elegant code. I just threw it together to meet my needs.

Also, I couldn't think of a time when a Sign-Up tool did not allow numbers or wasn't case sensitive so my passwords always have at least one number, one upper case letter, one lower case letter, and one special character. This means the minimum length is 4. Technically I can get around the special character requirement by just entering a letter if need be.

const getPassword = (length, arg) => {
  length = document.getElementById("lengthInput").value || 16;
  arg = document.getElementById("specialInput").value || "~!@#$%^&*()_+-=[]{}|;:.,?><";
  if (length < 4) {
    updateView("passwordValue", "passwordValue", "", "P", "Length must be at least 4");
    return console.error("Length must be at least 4")
  } else if (length > 99) {
    updateView("passwordValue", "passwordValue", "", "P", "Length must be less then 100");
    return console.error("Length must be less then 100")
  }
  const lowercase = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];
  const uppercase = lowercase.join("").toUpperCase().split("");
  const specialChars = arg.split("").filter(item => item.trim().length);
  const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  let hasNumber = false;
  let hasUpper = false;
  let hasLower = false;
  let hasSpecial = false;

  if (Number(length)) {
    length = Number(length)
  } else {
    return console.error("Enter a valid length for the first argument.")
  }

  let password = [];
  let lastChar;
  for (let i = 0; i < length; i++) {
    let char = newChar(lowercase, uppercase, numbers, specialChars);
    if (char !== lastChar) {
      password.push(char);
      lastChar = char
      if (Number(char)) {
        hasNumber = true
      }
      if (lowercase.indexOf(char) > -1) {
        hasLower = true
      }
      if (uppercase.indexOf(char) > -1) {
        hasUpper = true
      }
      if (specialChars.indexOf(char) > -1) {
        hasSpecial = true
      }
    } else {
      i--
    }
    if (i === length - 1 && (!hasNumber || !hasUpper || !hasLower || !hasSpecial)) {
      hasNumber = false;
      hasUpper = false;
      hasLower = false;
      hasSpecial = false;
      password = [];
      i = -1;
    }
  }

  function newChar(lower, upper, nums, specials) {
    let set = [lower, upper, nums, specials];
    let pick = set[Math.floor(Math.random() * set.length)];
    return pick[Math.floor(Math.random() * pick.length)]
  }
  updateView("passwordValue", "passwordValue", "", "P", password.join(""));
  updateView("copyPassword", "copyPassword", "", "button", "copy text");
  document.getElementById("copyPassword").addEventListener("click", copyPassword);
}

const copyPassword = () => {
  let text = document.getElementById("passwordValue").textContent;
  navigator.clipboard.writeText(text);
};

const updateView = (targetId, newId, label, element, method = '') => {
  let newElement = document.createElement(element);
  newElement.id = newId;
  let content = document.createTextNode(label + method);
  newElement.appendChild(content);

  let currentElement = document.getElementById(targetId);
  let parentElement = currentElement.parentNode;
  parentElement.replaceChild(newElement, currentElement);
}

document.getElementById("getPassword").addEventListener("click", getPassword);
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
</head>

<body>
  <div>
    <button id="getPassword">Generate Password</button>
    <input type="number" id="lengthInput" placeholder="Length">
    <input type="text" id="specialInput" placeholder="Special Characters">
    <p id="passwordValue"></p>
    <p id="copyPassword"></p>
  </div>

</body>

</html>

I got insprired by the answers above (especially by the hint from @e.vyushin regarding the security of Math.random() ) and I came up with the following solution that uses the crypto.getRandomValues() to generate a rondom array of UInt32 values with the length of the password length.

Then, it loops through the array and devides each element by 2^32 (max value of a UInt32) to calculate the ratio between the actual value and the max. possible value. This ratio is then mapped to the charset string to determine which character of the string is picked.

console.log(createPassword(16,"letters+numbers+signs"));
function createPassword(len, charset) {
    if (charset==="letters+numbers") {
        var chars = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
    } else if (charset==="letters+numbers+signs") {
        var chars = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!§$%&/?#+-_@";
    }
    var arr = new Uint32Array(len);
    var maxRange = Math.pow(2,32);
    var passwd = '';
    window.crypto.getRandomValues(arr);
    

    for (let i=0;i<len;i++) {
        var c = Math.floor(arr[i] / maxRange  * chars.length + 1);
        passwd += chars.charAt(c);
    }
    return passwd;
}

Thus, the code is able to use the advantage of the crypto-Class (improved security for the random value generation) and is adaptable to use any kind of charset the user wished. A next step would be to use regular expression strings to define the charset to be used.

Generate a random password of length 8 to 32 characters with at least 1 lower case, 1 upper case, 1 number, 1 special char (!@$&)

function getRandomUpperCase() {
   return String.fromCharCode( Math.floor( Math.random() * 26 ) + 65 );
}

function getRandomLowerCase() {
   return String.fromCharCode( Math.floor( Math.random() * 26 ) + 97 );
} 

function getRandomNumber() {
   return String.fromCharCode( Math.floor( Math.random() * 10 ) + 48 );
}

function getRandomSymbol() {
    // const symbol = '!@#$%^&*(){}[]=<>/,.|~?';
    const symbol = '!@$&';
    return symbol[ Math.floor( Math.random() * symbol.length ) ];
}

const randomFunc = [ getRandomUpperCase, getRandomLowerCase, getRandomNumber, getRandomSymbol ];

function getRandomFunc() {
    return randomFunc[Math.floor( Math.random() * Object.keys(randomFunc).length)];
}

function generatePassword() {
    let password = '';
    const passwordLength = Math.random() * (32 - 8) + 8;
    for( let i = 1; i <= passwordLength; i++ ) {
        password += getRandomFunc()();
    }
    //check with regex
    const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,32}$/
    if( !password.match(regex) ) {
        password = generatePassword();
    }
    return password;
}

console.log( generatePassword() );

Here's another approach based off Stephan Hoyer's solution

getRandomString (length) {
  var chars = 'abcdefghkmnpqrstuvwxyz23456789';
  return times(length, () => sample(chars)).join('');
}
function genPass(n)    // e.g. pass(10) return 'unQ0S2j9FY'
{
    let c='abcdefghijklmnopqrstuvwxyz'; c+=c.toUpperCase()+1234567890;

    return [...Array(n)].map(b=>c[~~(Math.random()*62)]).join('')
} 

Where n is number of output password characters; 62 is c.length and where e.g. ~~4.5 = 4 is trick for replace Math.floor

Alternative

function genPass(n)     // e.g. pass(10) return 'unQ0S2j9FY'
{
    let c='abcdefghijklmnopqrstuvwxyz'; c+=c.toUpperCase()+1234567890;

    return '-'.repeat(n).replace(/./g,b=>c[~~(Math.random()*62)])
} 

to extend characters list, add them to c e.g. to add 10 characters !$^&*-=+_? write c+=c.toUpperCase()+1234567890+'!$^&*-=+_?' and change Math.random()*62 to Math.random()*72 (add 10 to 62).

This method gives the options to change size and charset of your password.

function generatePassword(length=8, charset="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") {
    return new Array(length)
      .fill(null)
      .map(()=> charset.charAt(Math.floor(Math.random() * charset.length)))
      .join('');
}

console.log(generatePassword()); // 02kdFjzX
console.log(generatePassword(4)); // o8L5
console.log(generatePassword(16)); // jpPd7S09txv9b02p
console.log(generatePassword(16, "abcd1234")); // 4c4d323a31c134dd

A simple lodash solution that warranties 14 alpha, 3 numeric and 3 special characters, not repeated:

const generateStrongPassword = (alpha = 14, numbers = 3, special = 3) => {
  const alphaChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  const numberChars = '0123456789';
  const specialChars = '!"£$%^&*()-=+_?';
  const pickedChars = _.sampleSize(alphaChars, alpha)
    .concat(_.sampleSize(numberChars, numbers))
    .concat(_.sampleSize(specialChars, special));
  return _.shuffle(pickedChars).join('');
}

const myPassword = generateStrongPassword();

I also developed my own password generator, with random length (between 16 and 40 by default), strong passwords, maybe it could help.

function randomChar(string) {
  return string[Math.floor(Math.random() * string.length)];
}

// you should use another random function, like the lodash's one.
function random(min = 0, max = 1) {
 return Math.floor(Math.random() * (max - min + 1)) + min;
}

// you could use any shuffle function, the lodash's one, or the following https://stackoverflow.com/a/6274381/6708504
function shuffle(a) {
  for (let i = a.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [a[i], a[j]] = [a[j], a[i]];
  }

  return a;
}

function generatePassword() {
  const symbols = '§±!@#$%^&*()-_=+[]{}\\|?/<>~';
  const numbers = '0123456789';
  const lowercaseLetters = 'abcdefghijklmnopqrstuvwxyz';
  const uppercaseLetters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  const minCharsGroup = 4;
  const maxCharsGroup = 10;
  const randomSymbols = [...Array(random(minCharsGroup, maxCharsGroup))].map(() => randomChar(symbols));
  const randomNumbers = [...Array(random(minCharsGroup, maxCharsGroup))].map(() => randomChar(numbers));
  const randomUppercasesLetters = [...Array(random(minCharsGroup, maxCharsGroup))].map(() => randomChar(uppercaseLetters));
  const randomLowercasesLetters = [...Array(random(minCharsGroup, maxCharsGroup))].map(() => randomChar(lowercaseLetters));
  const chars = [...randomSymbols, ...randomNumbers, ...randomUppercasesLetters, ...randomLowercasesLetters];

  return shuffle(chars).join('');
}
const alpha = 'abcdefghijklmnopqrstuvwxyz';
const calpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const num = '1234567890';
const specials = ',.!@#$%^&*';
const options = [alpha, alpha, alpha, calpha, calpha, num, num, specials];
let opt, choose;
let pass = "";
for ( let i = 0; i < 8; i++ ) {
  opt = Math.floor(Math.random() * options.length);
  choose = Math.floor(Math.random() * (options[opt].length));
  pass = pass + options[opt][choose];
  options.splice(opt, 1);
}
console.log(pass);

Length 8 characters

At least 1 Capital

At least 1 Number

At least 1 Special Character

A modern and secure solution

Be aware of answers that rely on Math.random - they are not secure. This is an old question so it's no surprise that Math.random still pops up, but you should absolutely not be using it to generate a string to secure anything. If you really need to support browsers older than IE11, you should add a fallback to get the random values from the back-end, generated using a CSPRNG.

function generatePassword(length) {
  const crypto = window.crypto || window.msCrypto;

  if (typeof crypto === 'undefined') {
    throw new Error('Crypto API is not supported. Please upgrade your web browser');
  }

  const charset = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';

  const indexes = crypto.getRandomValues(new Uint32Array(length));

  let secret = '';

  for (const index of indexes) {
    secret += charset[index % charset.length];
  }

  return secret;
}

This is a simple example. You'd probably want to add special characters to the set and maybe enforce digits or symbols to be present.

Here's a quick dynamic modern solution which I thought I'll share

const generatePassword = (
  passwordLength = 8,
  useUpperCase = true,
  useNumbers = true,
  useSpecialChars = true,
) => {
  const chars = 'abcdefghijklmnopqrstuvwxyz'
  const numberChars = '0123456789'
  const specialChars = '!"£$%^&*()'

  const usableChars = chars
   + (useUpperCase ? chars.toUpperCase() : '')
   + (useNumbers ? numberChars : '')
   + (useSpecialChars ? specialChars : '')

  let generatedPassword = ''

  for(i = 0; i <= passwordLength; i++) {
    generatedPassword += usableChars[Math.floor(Math.random() * (usableChars.length))]
  }

  return generatedPassword
}
const length = 18; // you can use length as option or static
const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
const numbers = '0123456789';
const symbols = '!#$%&\()*+,-./:;<=>?@^[\\]^_`{|}~';

let password = '';

let validChars = '';

// all if conditions can be used to custom password
if (useLetters) {
    validChars += letters;
}

if (useNumbers) {
    validChars += numbers;
}

if (useSymbols) {
    validChars += symbols;
}

let generatedPassword = '';

for (let i = 0; i < length; i++) {
    const index = Math.floor(Math.random() * validChars.length);
    generatedPassword += validChars[index];
}

password = generatedPassword;

It's not very hard. You just have to learn about its concepts. You need to learn:

  1. Functions
  2. Variables
  3. Working with strings
  4. Mathematics
  5. loops
  6. DOM (if you're working with HTML) and the code is:
function gen(){
  // Save all the possible characters in a variable
  var chars = "abcdef";
  // make an empty variable to store random characters.
  var pw = "";
  // we need loop.
  // repeat four times then we have password with 4 characters
  for (var i=0; i<4; i++){
    // select random character
    var rand = Math.round(Math.random() * chars.length);
    // insert that random character to pw variable
    var pw += chars.charAt(rand);
  }
  // then return pw
  // Use console.log() || DOM || "return pw"
  return pw;
}

Based on @shani-kehati 's answer, with scrambling:

const Allowed = {
  Uppers: 'QWERTYUIOPASDFGHJKLZXCVBNM',
  Lowers: 'qwertyuiopasdfghjklzxcvbnm',
  Numbers: '1234567890',
  Symbols: '!@#$%^&*'
}

function getRandomChar(allowedChars) {
  return allowedChars.charAt(Math.floor(Math.random() * allowedChars.length))
}

function scrambleArray(chars) {
  return chars.sort(() => Math.random() - 0.5)
}

/**
 * Generates password of the given length with at least one upper, one lower, one number and one symbol.
 * @param length length of the password, min 4
 * @throws Error if length is less than 4
 */
function generatePassword(length = 8) {
  if (length < 4) {
    throw new Error('Password must be at least 4 characters long')
  }

  const chars = [
    getRandomChar(Allowed.Uppers),
    getRandomChar(Allowed.Lowers),
    getRandomChar(Allowed.Numbers),
    getRandomChar(Allowed.Symbols)
  ]

  for (let i = chars.length; i < length; i++) {
    chars.push(getRandomChar(Object.values(Allowed).join('')))
  }

  return scrambleArray(chars).join('')
}

console.log(generatePassword())
console.log(generatePassword(10))
console.log(generatePassword(10))

try {
  generatePassword(1)
} catch(e) {
  console.log(e.message)
}

Short Oneliner:

var pass=(a=>Array.from({length:11},_=>a[~~(Math.random()*a.length)]).join(''))('*$§!abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789');
console.log(pass);
Related