TypeScript

Crypto-Strong Random Password

admin by @admin ADMIN
17h ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Generate a strong random password in browser or modern Node. Uses crypto.getRandomValues with rejection sampling for an unbiased distribution.
TypeScript
Raw
export function generatePassword(length = 20, {
  lower = true, upper = true, digits = true, symbols = true,
} = {}): string {
  const sets: string[] = [];
  if (lower)   sets.push('abcdefghijklmnopqrstuvwxyz');
  if (upper)   sets.push('ABCDEFGHIJKLMNOPQRSTUVWXYZ');
  if (digits)  sets.push('0123456789');
  if (symbols) sets.push('!@#$%^&*()-_=+[]{};:,.<>?/~');

  const alphabet = sets.join('');
  if (!alphabet) throw new Error('Pick at least one character set');

  const buf = new Uint32Array(length);
  crypto.getRandomValues(buf);
  const limit = Math.floor(0x1_0000_0000 / alphabet.length) * alphabet.length;
  let out = '';
  let i = 0;
  while (out.length < length) {
    if (i >= buf.length) { crypto.getRandomValues(buf); i = 0; }
    const v = buf[i++]!;
    if (v < limit) out += alphabet[v % alphabet.length];
  }
  return out;
}

generatePassword(16);                              // 'X9k!nQ2pR&7vL@bW'
generatePassword(24, { symbols: false });          // no symbols
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.