Skip to main content
Back to Blog

Secure Password Generation: Why Length and Randomness Matter

Strong passwords and good generation habits still beat most attacks. Here's what makes a password hard to crack and how to create them.

Kashyap Thakar
10 min
SecurityPasswordsBest Practices
Secure Password Generation: Why Length and Randomness Matter

In an era of frequent data breaches, your password is often the only thing standing between an attacker and your personal information. Yet "123456" and "password" keep turning up on lists of the most common passwords. Why do we compromise our own security?

Entropy: The Measure of Strength

Security people talk about "entropy": a measure of unpredictability. A password like Tr0ub4dor&3 looks complex to a human, but it follows predictable patterns (a common word, familiar substitutions, a symbol and digit tacked on the end) that password-cracking tools are built to try early. Visual complexity and real unpredictability are different things.

True entropy comes from randomness in how the password was chosen, not from how it looks. A string of 16 characters picked uniformly at random has far more possibilities than a 16-character sentence, because the words of a sentence are not random and an attacker can guess them as words rather than as individual characters.

The Arithmetic of Password Strength

For a password in which every character is chosen uniformly at random from a character set of size C, the number of possible passwords of length L is CL. Entropy in bits is L x log2(C). Each additional bit doubles the number of possibilities. These figures were computed with Node.js:

Random passwordCharacter set sizePossibilitiesBits
8 digits10100,000,00026.6
8 lowercase letters26208,827,064,57637.6
8 letters and digits62218,340,105,584,89647.6
12 letters and digits623.2 x 10^2171.5
12 printable ASCII944.8 x 10^2378.7
16 lowercase letters264.4 x 10^2275.2
16 letters and digits624.8 x 10^2895.3
16 printable ASCII943.7 x 10^31104.9
20 lowercase letters262.0 x 10^2894.0

A few things stand out. Going from 8 to 12 characters of the same set multiplies the possibilities by 624, about 14.8 million. Length soon outweighs a bigger character set: 12 characters from all 94 printable ASCII symbols (78.7 bits) are slightly ahead of 16 lowercase letters (75.2 bits), but 20 lowercase letters (94.0 bits) are well ahead of them. Each character from a 94-symbol set contributes about 6.55 bits, each lowercase letter about 4.70 bits, and each decimal digit about 3.32 bits.

The important caveat: this table describes uniformly random passwords. A human-chosen password has far fewer effective possibilities than its length and character classes suggest, because people pick words, names and patterns. An attacker guesses the likely candidates first, so the table is an upper bound for chosen passwords, and an accurate figure only for generated ones. How many guesses per second an attacker can make depends on how the target stores passwords, which is why the storage section below matters as much as the password itself.

The Checklist for a Strong Password

  • ✓Length is King: For random passwords, length contributes more than adding character classes (see the table above). A 20-character password of just lowercase letters has more possibilities than a random 12-character one drawn from every printable character. Aim for at least 16 characters where the site allows it.
  • ✓True Randomness: Avoid dictionary words, birthdays, or keyboard patterns (like qwerty).
  • ✓Uniqueness: Never reuse passwords. If one site is breached, credential stuffing attacks will try the leaked password against your other accounts.

Why You Need a Generator

People are poor sources of randomness. We lean toward memorable words, familiar dates and predictable substitutions, and studies of leaked password lists consistently show the same popular choices repeating. A generator removes the human from the choice.

A random password generator, such as our Random Password Generator, takes the human out of the choice. Whatever tool you use, what matters is the source of randomness it draws from: it should be a cryptographically secure pseudo-random number generator (CSPRNG), as the next section explains.

Random Number Generators: getRandomValues vs Math.random

Math.random() is not designed for security and its output can be predictable, so it should not be used for passwords or tokens. In the browser, use crypto.getRandomValues(); in Node.js, crypto.randomInt() or crypto.randomBytes().

There is a second trap even with a secure source: modulo bias. If you take a random byte (0 to 255) and compute byte % 62 to pick one of 62 characters, 256 is not a multiple of 62, so some characters are slightly more likely than others. 256 % 62 is 8, so the first 8 characters each map to 5 of the 256 byte values while the other 54 map to 4. The fix is rejection sampling: discard values from the uneven tail and draw again.

function uniformIndex(max) {
  const limit = Math.floor(0x100000000 / max) * max; // largest multiple of max <= 2^32
  const buf = new Uint32Array(1);
  let x;
  do { crypto.getRandomValues(buf); x = buf[0]; } while (x >= limit);
  return x % max;
}

const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
function generate(length) {
  let out = "";
  for (let i = 0; i < length; i++) out += charset[uniformIndex(charset.length)];
  return out;
}

const pw = generate(16);
console.log(pw.length, /^[A-Za-z0-9]{16}$/.test(pw));
console.log("256 % 62 =", 256 % 62);
console.log("P(first char) =", (5 / 256).toFixed(5), "vs P(last char) =", (4 / 256).toFixed(5));

// Output (the password itself differs on every run):
// 16 true
// 256 % 62 = 8
// P(first char) = 0.01953 vs P(last char) = 0.01563

With a 32-bit draw the bias would be far smaller (232 % 62 is 4), but rejection sampling removes it entirely and costs almost nothing. In Node.js, crypto.randomInt(max) already does this for you.

How Attackers Get Passwords

Understanding attack methods helps you choose better defenses:

1. Dictionary Attacks

Attackers start with lists of common passwords, dictionary words, and passwords exposed in earlier breaches, often combined with rules that mimic habits such as capitalizing the first letter or appending digits. A password that appears on such a list, or is a small variation of something that does, needs far fewer guesses than its length suggests.

2. Brute Force Attacks

Automated tools try every possible combination of characters. The work grows exponentially with length: a 6-character lowercase password has 266 = 308,915,776 possibilities, while a 12-character one has 2612, roughly 9.5 x 1016. How fast guesses can be made depends on the attacker and on how the password is stored, so treat the possibility count as the measure and not a promise of any particular time.

3. Rainbow Tables and Fast Hashes

Precomputed tables of password hashes let attackers look up hashes of common passwords instead of computing them. Adding a unique random salt to each password before hashing defeats precomputed tables, and a deliberately slow password hash (see below) limits how quickly stolen hashes can be tested.

4. Credential Stuffing

Credentials leaked from one service are replayed against others. No password strength helps if the same password is used in two places, which is why uniqueness is on the checklist above.

5. Social Engineering and Phishing

Attackers use personal information (birthdays, pet names, favorite sports teams) to guess passwords, or trick you into typing the password into a fake page. A strong password does nothing against the second, which is one reason to add a second factor or passkeys.

Password Generation Strategies

Random Character Passwords

The strongest passwords for a given length are uniformly random strings of characters. A good generator should:

  • Use cryptographically secure random number generators
  • Allow customization of length and character sets
  • Exclude ambiguous characters (like 0, O, I, l) if desired
  • Provide multiple password options to choose from

Passphrase Approach

Passphrases made of several randomly chosen words, such as correct-horse-battery-staple, are easier to remember and type. The key word is randomly: the words must be picked by a generator, not by you. With a list of 7,776 words (the size of the common Diceware list, 65), each word adds log2(7776) = 12.9 bits:

  • 4 words: 51.7 bits (about 3.7 x 1015 combinations)
  • 5 words: 64.6 bits (about 2.8 x 1019)
  • 6 words: 77.5 bits (about 2.2 x 1023)

For the same character count, random characters pack in more entropy, but a six-word passphrase is comparable to a 12-character random printable-ASCII password (78.7 bits) while being far easier to type on a phone or into a device that has no password manager. Use passphrases for the few secrets you must memorize, such as a password manager's master password, and random strings for everything else.

How Services Should Store Passwords

If you build a service, the strength of users' passwords is only half the story. Never store passwords in plain text or with a fast general-purpose hash such as plain SHA-256 or MD5. Use a purpose-built password hashing function such as Argon2, scrypt or bcrypt, with a unique random salt per password, and tune its cost settings according to current guidance for the function you choose. Salting means two users with the same password get different stored values, and the slowness limits how fast stolen hashes can be tested. Node.js ships scrypt in its crypto module:

import { scryptSync, randomBytes, timingSafeEqual } from "node:crypto";

function hashPassword(password) {
  const salt = randomBytes(16);
  const hash = scryptSync(password, salt, 32);
  return salt.toString("hex") + ":" + hash.toString("hex");
}

function verify(password, stored) {
  const [saltHex, hashHex] = stored.split(":");
  const hash = scryptSync(password, Buffer.from(saltHex, "hex"), 32);
  return timingSafeEqual(hash, Buffer.from(hashHex, "hex"));
}

const a = hashPassword("hunter2"), b = hashPassword("hunter2");
console.log("same password, different stored values:", a !== b);
console.log("verify correct:", verify("hunter2", a));
console.log("verify wrong:", verify("hunter3", a));

// Output:
// same password, different stored values: true
// verify correct: true
// verify wrong: false

This sample uses the scrypt defaults and is meant to show the shape of salt, hash and constant-time comparison. For production, follow your framework's or library's recommended settings. For background on hash functions in general, see hashing algorithms explained, and you can experiment with digests in the Hash Generator.

What Current Guidance Says

NIST Special Publication 800-63B-4, the US digital identity guidelines (final since July 2025), rejects the old habits of mandatory composition rules (one uppercase, one symbol) and forced periodic password changes. Verifiers must not impose composition rules and must not require periodic changes, but must force a change when there is evidence of compromise. They must compare new passwords against a blocklist of known-compromised and commonly used values, should accept passwords of at least 64 characters, and must require at least 15 characters when the password is the only authentication factor (8 when it is used inside multi-factor authentication). It is a useful reference if you are designing a sign-up form. Many sites still enforce legacy rules, so you may have to satisfy them even when they do not improve security.

Best Practices

  • Use a Password Manager: You shouldn't know your passwords. Let the manager generate and store them. Modern password managers use strong encryption and can generate truly random passwords for each account.
  • Enable 2FA: A second factor adds protection that a password alone cannot provide. Even if your password is exposed, the attacker still needs the second factor. Authenticator apps and hardware security keys are generally considered stronger than codes sent by SMS, which NIST treats as a restricted authenticator.
  • Prefer Passkeys Where Offered: Passkeys use public-key cryptography instead of a shared secret, and are bound to the site they were created for, so they cannot be typed into a look-alike phishing page.
  • Rotate on Breach: Change passwords immediately if a service you use reports a breach. Use Have I Been Pwned to check if your email has been involved in data breaches.
  • Never Reuse Passwords: Each account should have a unique password. Credential stuffing attacks rely on password reuse.
  • Check Password Strength: Use our Password Checker to verify your password strength before using it.

Password Manager Integration

Modern password managers integrate with browsers and mobile apps, making it seamless to use strong, unique passwords everywhere. They can:

  • Auto-fill passwords on websites
  • Generate passwords when creating new accounts
  • Detect weak or reused passwords
  • Alert you to data breaches
  • Sync across all your devices securely

Auto-fill has a small security benefit of its own: it fills credentials by matching the site address, so it will not offer your password on a look-alike domain the way a human might type it.

Generate Secure Passwords

Creating strong passwords manually is nearly impossible. Our Random Password Generator offers:

  • Adjustable length and character sets
  • Options to exclude similar-looking and ambiguous characters
  • Generation in your browser with the Web Crypto random source (crypto.getRandomValues, with rejection sampling to avoid modulo bias), so the password is not sent to a server

Combine this with a password manager, and you'll have strong, unique passwords for every account without the mental burden of remembering them. If you are curious how a browser-only tool can keep your data private, read why privacy-first developer tools matter.

Frequently Asked Questions

How long should a password be?

For a randomly generated password, 16 or more characters is a sensible target where the site allows it, since 16 random letters and digits gives about 95 bits. Sites that cap length force a shorter choice, in which case use all character types.

Is a passphrase better than a random password?

Only if the words are chosen randomly by a generator. A random six-word passphrase from a 7,776-word list has about 77.5 bits, which is comparable to a 12-character random password and much easier to remember and type. A phrase you invent yourself has far less entropy.

Are password generators safe?

A generator is safe when it uses a cryptographically secure source such as crypto.getRandomValues() and generates the password on your device. Avoid tools that rely on Math.random() or send the password to a server.

Should I change my passwords regularly?

Not on a fixed schedule, according to NIST SP 800-63B-4, which says verifiers must not require periodic changes. Change a password when you know or suspect it was exposed, and always when a service reports a breach.

Do I still need a strong password if I use 2FA?

Yes. A second factor is an extra barrier, not a replacement. A strong, unique password reduces the chance that an attacker gets to the second factor at all.

Written by

Spotted a mistake? Let me know