All articles

How to generate a secure random password in JavaScript

· 3 min read

Generating a password looks like a one-liner: pick random characters from a string. The details decide whether the result is actually unpredictable. The two common mistakes are using Math.random() and mapping random numbers onto the alphabet in a way that makes some characters more likely than others.

Don't use Math.random()

Math.random() is a fast pseudo-random generator meant for games, animations and sampling. It isn't designed to be unpredictable: with enough outputs, its internal state can be reconstructed and future values predicted. MDN says explicitly not to use it for anything security-related.

Use the cryptographically secure generator built into every browser and Node.js:

const bytes = new Uint32Array(4);
crypto.getRandomValues(bytes); // fills the array with secure random values

In Node.js, the global crypto.getRandomValues is available from Node 19 (earlier versions have it as require("node:crypto").webcrypto.getRandomValues), and crypto.randomInt(max) from node:crypto gives an unbiased integer directly.

Avoid modulo bias

The tempting way to pick a character is alphabet[byte % alphabet.length]. With a Uint8Array, a byte has 256 values. For a 62-character alphabet, 256 isn't a multiple of 62, so the first 8 characters (256 − 4 × 62 = 8) get one extra chance each: they're about 25% more likely than the rest.

Two fixes:

  • Rejection sampling: discard values above the largest multiple of the alphabet size, and draw again. This is exactly uniform.
  • Use larger random values: with 32-bit numbers the bias for a 62-character alphabet is around one in 70 million, which is negligible in practice. Rejection sampling is still the cleaner choice for a library.
function randomIndex(max) {
  // Largest multiple of max that fits in 32 bits; values at or above it are rejected.
  const limit = Math.floor(0x100000000 / max) * max;
  const buffer = new Uint32Array(1);
  do crypto.getRandomValues(buffer);
  while (buffer[0] >= limit);
  return buffer[0] % max;
}

A complete generator

const SETS = {
  upper: "ABCDEFGHJKLMNPQRSTUVWXYZ",  // no I or O
  lower: "abcdefghijkmnopqrstuvwxyz", // no l
  digits: "23456789",                 // no 0 or 1
  symbols: "!@#$%^&*()-_=+[]{}:,.?",
};

function generatePassword(length = 20, sets = Object.values(SETS)) {
  if (length < sets.length) throw new Error("Length is shorter than the number of required sets");
  const alphabet = sets.join("");
  // One character from each set, so every selected type is present
  const chars = sets.map((set) => set[randomIndex(set.length)]);
  while (chars.length < length) chars.push(alphabet[randomIndex(alphabet.length)]);
  // Fisher-Yates shuffle, so the guaranteed characters aren't always at the start
  for (let i = chars.length - 1; i > 0; i--) {
    const j = randomIndex(i + 1);
    [chars[i], chars[j]] = [chars[j], chars[i]];
  }
  return chars.join("");
}

generatePassword(); // e.g. 'kL3RTnj]Q&p-#5&$LaDL'

Leaving out look-alike characters (I, l, 1, O, 0) makes passwords easier to read aloud or type from another screen, at the cost of a slightly smaller alphabet.

Guaranteeing one character from each set slightly reduces the number of possible passwords, but it means the result passes "must contain a digit" rules on the first try.

How strong is it? Entropy

For a password chosen uniformly at random, strength is measured in bits of entropy:

entropy = length × log2(alphabet size)
Alphabet Size Bits per character 16 characters 20 characters
Digits 10 3.3 53 66
Lowercase 26 4.7 75 94
Letters and digits 62 5.95 95 119
Printable ASCII 94 6.55 105 131

Each extra bit doubles the number of guesses an attacker needs. Around 80 bits is far beyond online guessing and very expensive offline; 100+ bits is comfortable for anything stored in a password manager.

This formula only applies to random passwords. A human-chosen password like Summer2026! has far less entropy than its length suggests, because attackers try common patterns first.

Random tokens

For API keys, reset tokens and session IDs you don't need a readable alphabet. Generate bytes and encode them:

const bytes = crypto.getRandomValues(new Uint8Array(32)); // 256 bits

const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");

// Node.js: URL-safe and compact
const token = Buffer.from(bytes).toString("base64url");

Encoding bytes has no bias problem, since every byte maps directly to output characters. Base64URL keeps the token short and safe in URLs.

In Python

The secrets module is the standard choice:

import secrets, string

alphabet = string.ascii_letters + string.digits + "!@#$%^&*"
password = "".join(secrets.choice(alphabet) for _ in range(20))
token = secrets.token_urlsafe(32)

Never use the random module for passwords or tokens.

Handling passwords after generating them

  • Show the password once over HTTPS, and never write it to logs or analytics.
  • Store only a slow password hash such as Argon2id, scrypt or bcrypt. A fast hash like SHA-256 is the wrong tool for passwords, for reasons covered in SHA-256 with Web Crypto.
  • Follow NIST SP 800-63B: allow long passwords and paste, check against known breached passwords, and don't force arbitrary composition rules or periodic changes on users.

Frequently asked questions

How long should a generated password be?

For passwords stored in a password manager, 16 to 20 random characters from a mixed alphabet is plenty. Length adds more strength than extra symbol types.

Is crypto.randomUUID() a good password?

It contains 122 random bits, which is strong, but it uses only hex characters and dashes. It's fine for tokens; for passwords, a generator with a larger alphabet gives the same strength in fewer characters.

Should I store generated passwords?

Store only a slow, salted hash (Argon2id, scrypt or bcrypt) on the server. Show the password to the user once and never log it.

Are passphrases better?

Several random words from a large list (diceware style) give good entropy and are easier to type and remember. Six words from a 7,776-word list give about 77 bits.

Further reading