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
Create a free account and build your private vault. Share publicly whenever you want.