Password storage

Why a fast hash is the wrong tool, what salt and a work factor each buy, and the bcrypt string that carries both inside it.

11 min read🛡️ Application Security

You are not storing passwords. You are storing something that lets you check a password without being able to recover it — and the difference is what decides whether a stolen database is an incident or a catastrophe.

The rules are settled, they are short, and nearly every way of getting this wrong comes from applying general-purpose engineering instincts to a problem where they are backwards.

A fast hash is the wrong tool, and here is why

The instinct is: hash it, store the hash, compare hashes. The hash is one-way, so the password cannot be recovered. Correct — and insufficient:

plaintext
### sha256 #1: f52fbd32b2b3b86ff88ef6c490628285f482af15ddcb29541f94bcf526a3f6c7
### sha256 #2: f52fbd32b2b3b86ff88ef6c490628285f482af15ddcb29541f94bcf526a3f6c7

The same password produces the same hash, every time, on every machine. Two consequences follow, and they are the whole problem:

  • Anyone with the stolen table can see which users share a password, without cracking anything.
  • The attacker does not need to reverse the hash. They hash a list of common passwords once and look yours up. The work is done in advance and reused against every database in the world.

And SHA-256 is fast — that is what it was designed for. Fast is exactly wrong here: a modern GPU computes billions of them per second, so "guess and check" is cheap at a scale that makes most human-chosen passwords findable.

Salt makes each hash unique; a slow algorithm makes each guess expensive

A salt is a random value stored alongside the hash and mixed in before hashing. Now the same password produces a different hash for every user, so a precomputed table is useless and identical passwords are no longer visible.

A work factor makes the function deliberately slow, and adjustable, so it can be made slower as hardware gets faster.

BCryptPasswordEncoder does both, and the salt handling is the part worth seeing, because it surprises people:

plaintext
### bcrypt #1: $2a$10$nFGmQBrMGQjDbSCALpjwG.IlGuqnDTnO3.be3NnMlTyMDuRTetdYO
### bcrypt #2: $2a$10$zLVHB530DuJyMSSbezUfa.nrfZMvKfT4zzeFqjTWOEtdIFiyYD0T6
### equal as strings? false
### does #1 verify the password? true
### does #2 verify the password? true
### does #1 verify a wrong one?  false

The same password, hashed twice, produced two completely different strings — and both verify it. That is not magic. Read the format:

plaintext
$2a$   10   $   nFGmQBrMGQjDbSCALpjwG.   IlGuqnDTnO3.be3NnMlTyMDuRTetdYO
 │      │       └── the 22-char salt      └── the hash
 │      └── work factor: 2^10 iterations
 └── the bcrypt variant

The salt is inside the stored string. There is no separate salt column to design, no salt to manage, and no way to forget to store it. matches() reads the salt and the cost out of the stored value, applies them to the candidate password, and compares.

What the work factor costs, measured

Each increment doubles the work. On this machine:

plaintext
### cost  4:    1.2 ms
### cost  8:   17.2 ms
### cost 10:   68.2 ms
### cost 12:  273.6 ms

The number to choose is not a constant from a blog post; it is whatever takes about 100 ms on your production hardware, measured there. Slow enough that offline guessing is expensive, fast enough that logging in feels instant and a burst of logins does not exhaust your threads.

That last clause is a real operational consideration: at cost 12, a hundred concurrent logins is 27 seconds of pure CPU. Password verification is the one place in a web application where you are deliberately burning CPU, and it wants to be sized like any other capacity decision.

Because the cost is stored in the hash, you can raise it later: on the next successful login, re-encode with the new factor and update the row. Old hashes keep working; new ones are stronger.

Which algorithm

Use it
bcryptthe safe default; everywhere, battle-tested, in Spring Security already
Argon2idthe current recommendation where you can choose; resists GPU and memory-hard attacks
scryptfine; memory-hard, less common in Java
PBKDF2acceptable, and often mandated by compliance; weakest of the four against GPUs
MD5, SHA-1, SHA-256, SHA-512never, alone, for passwords

bcrypt has one quirk worth knowing: it truncates at 72 bytes. A longer passphrase is silently cut, which matters if you accept long ones. Argon2id does not have this limit.

Spring Security's DelegatingPasswordEncoder is what makes migration possible. It stores the algorithm as a prefix — {bcrypt}$2a$10$... — so a single column can hold hashes made by different algorithms, and you can move to Argon2id by encoding new and re-encoding on login.

The rest of the login path

Hashing correctly and then leaking the answer elsewhere is common enough to be worth listing:

  • Never log the password. Not at debug, not in a request dump, not in an exception message. A toString() on a request DTO that includes a password field will eventually end up in a log line.
  • Compare in constant time. encoder.matches() does this; a hand-written hash.equals(stored) on a raw hash does not, and a timing difference is measurable over a network.
  • Say the same thing for both failures. "No such user" and "wrong password" are different answers, and returning different ones tells an attacker which email addresses are registered — including on the registration and password-reset paths, where the leak is easiest to forget.
  • Rate-limit login attempts per account and per IP. Hashing is slow by design, which also means an unlimited login endpoint is a cheap denial-of-service against your own CPU.
  • Do not impose rules that make passwords worse. Length is what matters; forced rotation, mandatory symbols and a 16-character maximum all push people towards Password1! and a sticky note. Check the candidate against a list of known-breached passwords instead.

Under the hood: why scrypt is memory-hard, and what that costs in production

bcrypt and PBKDF2 make guessing expensive by burning CPU time — more rounds, more iterations. That is real protection, and it has a weakness: a CPU is the one thing an attacker can throw thousands of at a problem cheaply, in parallel, on hardware built for exactly that (a GPU, or purpose-built ASICs for the popular algorithms). scrypt (and Argon2id after it) adds a second resource an attacker cannot get around by adding more cores: memory.

scrypt's core is a construction called ROMix. It fills a large buffer — N blocks, each built by chaining a fast mixing function (Salsa20/8) — and then reads back through that buffer in an order that depends on the data it already computed, not a fixed order a prefetcher could predict. Two consequences follow directly from that shape:

  • The buffer has to exist, in full, for the whole computation. You cannot trade memory for time the way you can with most algorithms — there is no shortcut that recomputes a block instead of storing it without also recomputing large parts of the chain, which is slower than just keeping the buffer.
  • Every parallel attempt needs its own buffer. A CPU or a general-purpose GPU has comparatively little fast memory per core, so N parallel guesses need N times the memory, which does not scale the way N parallel CPU cycles do. That is the actual mechanism behind "memory-hard": it does not make one guess slower in a way a faster chip fixes, it makes many simultaneous guesses expensive in a resource that does not get cheaper as fast as compute does.

This project's own hasher (lib/server/password.ts) is scrypt, not bcrypt — the lesson's table above still holds; it is simply this codebase's real choice from that same row. It stores a hash as scrypt$N$r$p$salt$hash, at N = 2^17 (131072), r = 8, p = 1, a 16-byte random salt and a 64-byte derived key — the same "parameters travel with the hash" idea as bcrypt's $2a$10$..., so a verify reads its own cost from the stored string rather than from a config value that could drift out of sync with old rows. The module's own comment gives the exact memory a set of parameters costs: 128·r·(N+2) + 128·r·p bytes — at this project's numbers, close to 128 MB per hash. computable() refuses to run a hash whose parameters would exceed a configured cap (MAX_MEMORY, 256 MB) rather than attempting it — because those parameters come out of the database, and a corrupted or tampered row asking for gigabytes must not be allowed to take the process down trying to honour it.

The comparison itself uses timingSafeEqual, not Buffer.equals or === — a derived key and the stored key are compared byte-for-byte in constant time, so the expensive part (the actual scrypt derivation, which dominates the timing by orders of magnitude) is the only thing that legitimately takes measurable time; the final yes/no does not leak how many leading bytes matched.

Try it yourself

Trace why a stored salt makes two hashes of the same password come out different

This is not real scrypt — no cryptographic hash is being computed — but it mirrors, in miniature, the one property a salt exists to provide: mixing in a random value before hashing means the same password produces a different stored output for two different salts, and the same output when the salt is also the same.

java
java.security.MessageDigest md = java.security.MessageDigest.getInstance("SHA-256");
String password = "hunter2";
 
md.update("salt-one".getBytes());
md.update(password.getBytes());
String hash1 = HexFormat.of().formatHex(md.digest());
 
md.reset();
md.update("salt-one".getBytes());
md.update(password.getBytes());
String hash2 = HexFormat.of().formatHex(md.digest());
 
md.reset();
md.update("salt-two".getBytes());
md.update(password.getBytes());
String hash3 = HexFormat.of().formatHex(md.digest());
 
System.out.println("hash1 == hash2 (same salt): " + hash1.equals(hash2));
System.out.println("hash1 == hash3 (different salt): " + hash1.equals(hash3));

Before running it: if an attacker stole a database where every row used the same fixed salt instead of a random one per row, would a precomputed table of common passwords still be useless against it?

A shared salt is not the same as no salt, but it is not the same as a per-row salt either

No — a single fixed salt shared by every row defeats a generic precomputed table (one built without that salt in mind), but it does not defeat a table built specifically for that one salt, and an attacker who has the stolen database also has the shared salt sitting right there in every row. They would need to precompute only once, for that one salt, and the result works against every user in the table simultaneously — exactly the "identical passwords are visible" problem this lesson opened with, just one level removed. A per-row random salt, as SALT_BYTES random bytes generated fresh for every hash in this project's own code, means an attacker who wants to attack more than one row has to redo the entire expensive computation once per row, with no reuse — which is the whole point.

Misconceptions

  • "A slow hash makes brute force impossible." It makes each guess expensive, not impossible — a work factor is a dial, not a wall. It buys time (and, for weak or reused passwords, often enough time that the account is changed or the breach is noticed first), and it has to be revisited as hardware gets faster, which is exactly why the parameters travel with the hash instead of being assumed from a constant.
  • "bcrypt/Argon2/scrypt are a form of encryption, so a 'strong enough' one can be decrypted to recover the password." They are one-way functions by design — there is no key that reverses them, and "cracking" a hash means guessing candidate passwords and hashing each one to check, never inverting the function itself. If a system can produce your original password back, it was never hashing it in the first place.

Sources

  • OWASP Password Storage Cheat Sheet.
  • NIST Special Publication 800-63B — Digital Identity Guidelines, Authentication and Lifecycle Management.
  • RFC 7914 — The scrypt Password-Based Key Derivation Function.
  • lib/server/password.ts (this project's own scrypt hasher and its documented parameters).
Progress is saved on this device and to your account when signed in.