How to Create Strong Passwords: A Developer's Security Guide
Weak passwords are the most common entry point for breaches. This guide covers entropy, password policies, secure storage with bcrypt and Argon2, and how to build a compliant password generator.
Two Different Problems
“Strong passwords” covers two jobs that are often mixed up. As a user, you need passwords that an attacker cannot guess. As a developer, you need a sign-up policy that does not push people towards bad choices, and a storage scheme that keeps passwords safe even after your database leaks. This guide covers both, with code you can run in Node.js 20 or later.
Entropy: Only Meaningful for Random Passwords
Password strength is usually expressed in bits of entropy: if a password is picked uniformly at random from N possibilities, its entropy is log₂(N). For a password of length L drawn from an alphabet of C symbols, that is L × log₂(C). Every extra bit doubles the attacker's work.
The formula has one condition people forget: the password must actually be random.P@ssw0rd uses four character classes, so a naive meter scores it as 8 × log₂(94) ≈ 52 bits. In reality it is one of the first guesses in every cracking wordlist. The Have I Been Pwned range API (shown below) reported it in more than six million breach records when this article was updated. Human-chosen passwords follow patterns — a capital first letter, a digit at the end, “a” replaced by “@” — and crackers apply those rules first.
For generated secrets the math is exact. The table assumes an offline attacker making 1010 guesses per second, a reasonable figure for a fast, unsalted hash on GPU hardware, and shows the average time to find the password (half the space).
| Randomly generated | Entropy | Average time at 10¹⁰ guesses/s |
|---|---|---|
| 8 lowercase letters | 37.6 bits | about 10 seconds |
| 4 words from the 7,776-word Diceware list | 51.7 bits | about 2 days |
| 6 Diceware words | 77.5 bits | about 350,000 years |
| 12 characters, all 94 printable ASCII | 78.7 bits | about 750,000 years |
| 20 characters, letters + digits (62) | 119.1 bits | far beyond any feasible attack |
Two lessons follow. Length beats symbol variety: adding characters grows entropy linearly, while moving from 62 to 94 symbols adds only 0.6 bits per character. And passphrases are fine if the words are chosen by dice or a CSPRNG — a four-word phrase you picked yourself from a song lyric is not 51.7 bits. For accounts you control, a password manager plus a generated 16–20 character password removes the guesswork. The password generator shows the entropy of each configuration as you change length and character sets.
What NIST SP 800-63B Says About Password Policy
NIST Special Publication 800-63B is the reference most security teams follow. Revision 4, finalised in 2025, keeps the direction of earlier versions and makes several points stricter. For a sign-up form, the practical rules are:
- Minimum length 15 when the password is the only factor; 8 is allowed when it is used together with another factor (MFA).
- Allow at least 64 characters, accept spaces and Unicode, and never silently truncate.
- No composition rules such as “one uppercase, one digit, one symbol”. They produce predictable passwords like
Summer2026!. - No periodic expiry. Force a change only when there is evidence of compromise.
- Check against a blocklist of breached, common and context-specific passwords (the site name, the username).
- Allow paste and password managers. Blocking paste mainly punishes people using long generated passwords.
- No security questions or password hints.
- Rate-limit failed attempts on the account so online guessing stays slow.
If your current form says “8–16 characters, must include a symbol, expires every 90 days”, every part of that sentence contradicts the guideline.
Worked Example: Blocklist Check Without Sending the Password
Have I Been Pwned exposes a k-anonymity range API. You hash the password with SHA-1, send only the first five hex characters, and receive every breached hash suffix that shares the prefix, with a count. The full password and full hash never leave your server.
import crypto from 'node:crypto';
async function pwnedCount(password) {
const sha1 = crypto.createHash('sha1').update(password, 'utf8')
.digest('hex').toUpperCase();
const prefix = sha1.slice(0, 5), suffix = sha1.slice(5);
const res = await fetch(`https://api.pwnedpasswords.com/range/${prefix}`,
{ headers: { 'Add-Padding': 'true' } });
for (const line of (await res.text()).split('\n')) {
const [s, count] = line.trim().split(':');
if (s === suffix) return Number(count);
}
return 0;
}
await pwnedCount('P@ssw0rd'); // → 6421042 (at time of writing)
await pwnedCount('7JtMosKLKkJwrvWaFWPm'); // → 0SHA-1 is fine here because it is only an index into a public list, not a storage scheme. The Add-Padding header adds dummy rows so response size does not leak which prefix you asked for. Reject the password, or warn, when the count is above zero.
Generating Passwords Correctly
Use the platform's cryptographic random generator (crypto.getRandomValues in browsers and Node, secrets in Python), never Math.random(), whose output is predictable once an attacker has seen enough of it. A second, subtler bug is modulo bias: mapping a random byte (0–255) onto a 94-character alphabet with byte % 94 makes the first 68 characters appear three times as often as the rest (256 = 2 × 94 + 68). Rejection sampling fixes it:
// Node 20+ or any modern browser
function generatePassword(length = 20,
charset = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789') {
const limit = 256 - (256 % charset.length); // largest multiple of the alphabet size
const out = [];
while (out.length < length) {
for (const b of crypto.getRandomValues(new Uint8Array(length))) {
if (b < limit && out.length < length) out.push(charset[b % charset.length]);
}
}
return out.join('');
}
generatePassword(); // e.g. '7JtMosKLKkJwrvWaFWPm' — 20 × log2(57) ≈ 116.7 bitsThe default alphabet drops look-alike characters (I, O, l, 0, 1), which costs a little entropy per character but avoids transcription errors when someone has to type the password from a screen. Drawing from 32-bit values instead of bytes also makes the bias negligible, which is the approach the StackUtils generator takes.
Storing Passwords: Slow, Salted, Upgradable
Never store a reversible form of a password, and never use a fast hash such as SHA-256 or MD5 for it, salted or not — fast is exactly what an attacker with a stolen table wants (see SHA-256 and hashing explained). Use a password hashing function with a unique salt per user and a tunable cost. The OWASP Password Storage Cheat Sheet gives these minimum configurations:
| Algorithm | Minimum parameters | When to choose it |
|---|---|---|
| Argon2id | m = 19 MiB, t = 2, p = 1 | First choice for new systems |
| scrypt | N = 2¹⁷, r = 8, p = 1 | Argon2 unavailable; built into Node and Python |
| bcrypt | cost 10 or higher; 72-byte input limit | Legacy systems, wide library support |
| PBKDF2-HMAC-SHA256 | 600,000 iterations | FIPS-140 compliance required |
import argon2 from 'argon2'; // npm i argon2
// Registration
const hash = await argon2.hash(password, {
type: argon2.argon2id,
memoryCost: 19456, // KiB = 19 MiB
timeCost: 2,
parallelism: 1,
});
// → '$argon2id$v=19$m=19456,t=2,p=1$<salt>$<hash>'
// Login
if (await argon2.verify(hash, attempt)) {
if (argon2.needsRehash(hash, { memoryCost: 19456, timeCost: 2, parallelism: 1 })) {
// re-hash with the current parameters and save
}
}The salt and parameters are stored inside the hash string, so you can raise the cost later and re-hash each user transparently at their next successful login. Benchmark on your production hardware: a common target is a few hundred milliseconds per hash at peak login load.
Common Mistakes
- bcrypt's 72-byte limit. Most bcrypt libraries silently ignore everything after byte 72, so two long passwords sharing a prefix verify as equal. The limit is bytes, not characters: 18 emoji are already 72 bytes in UTF-8. Prefer Argon2id for new code.
- Unicode normalisation. “café” can be typed as one code point (é) or two (e + combining accent), and the two forms hash differently. Normalise with
password.normalize('NFKC')before hashing, both at registration and at login. - Trimming or lower-casing input. Spaces are valid password characters; do not strip them.
- Logging request bodies. A debug logger that dumps the login payload stores every password in plain text in your log pipeline. Redact the field at the logger level.
- Revealing which part failed. “Unknown email” versus “wrong password” lets attackers enumerate accounts. Return the same message and similar response time for both.
- Comparing hashes with
===. Use the library's verify function, which compares in constant time.
Checklist for a Sign-Up and Login Flow
- Minimum 15 characters (8 if MFA is mandatory), maximum at least 64, no composition rules.
- Breached-password check with the k-anonymity API or a local copy of the list.
- Argon2id (or scrypt/bcrypt/PBKDF2 with the parameters above), rehash on login when parameters change.
- HTTPS only; password fields redacted in logs and error reports.
- Rate limiting per account and per IP; generic error messages.
- Offer a second factor — an authenticator app or a passkey.
Generate a random password
Pick length and character sets, see the entropy in bits, and copy a password generated locally with crypto.getRandomValues. Nothing is sent to a server.