Skip to content

How passwords should be stored

BasicsUnder the hood

A login form has to check your password, yet the server should never be able to tell anyone what it is. Here is how that works, and why the choice of hash decides what a stolen database gives away.

01 The job: check a password you never keep

When Bo signs up, the server needs to keep something so that next week it can tell whether he typed the same password again. The obvious thing is the password itself.

SQL
SELECT email, password FROM users;
email | password
--------------+-----------
bo@x.com | 123456
dee@x.com | password

Databases leak: a stolen backup, a SQL injection, a laptop with a dump on it. And people reuse passwords, so a leaked table opens their email and bank too. The goal is a stored value that lets you check a password but gives an attacker as little as possible.

02 Hash it, do not encrypt it

A hash function turns any input into a fixed-size value, and there is no way to run it backwards. At sign-in you hash what the user typed and compare it with the stored hash. The password itself is never written down.

Encryption is the wrong tool here: it is built to be reversed. Whoever gets the key, often from the same server as the database, reads every password at once.

Plain textRead itThe leak is the list of passwords.
EncryptedDecrypt itOne stolen key turns every row back into a password.
HashedGuess itNothing to reverse. The attacker has to guess, hash, and compare.

03 Why a fast hash still leaks

"Guess it" sounds safe until you see how cheap a guess is. SHA-256 was designed to be fast: a single modern GPU computes billions of SHA-256 hashes per second (approximate, from public benchmarks). Real people pick from a small set of likely passwords, and lists of millions of leaked ones are easy to find.

Cracking a leaked table of fast hashes
Step 1 of 5
Cracked 0 of 4
Leaked users table · unsalted SHA-256
stored hash (first 8)password
ana4568199f
bo8d969eef
cy8d969eef
dee5e884898
Attacker’s guesses, each hashed once
Empty
  • just hashed
  • cracked by this guess
  • not known yet

The attacker has a copy of the users table. Each row holds a SHA-256 hash, not a password, so nothing is readable yet.

0 guesses hashed

Two things went wrong. Every guess was hashed once and checked against every row, so identical passwords fell together. And each guess cost almost nothing. A good scheme fixes both.

04 Salt: a different hash for every user

A salt is a random value, typically 16 bytes, made fresh for each user at sign-up. You hash the salt together with the password and store the salt next to the hash. It is not secret.

Bo and Cy both pick 123456. With a random salt each, their stored hashes have nothing in common.
users table · salted scrypt
salt (first 8)stored hash (first 8)
bokKz97gL2AF+xhB5S
cyM3MW6GROPKkKkj31

Real values from two runs of the code below with the same password. Cracking Bo now teaches the attacker nothing about Cy: every guess must be hashed again for every user.

Now one guess no longer checks the whole table: the attacker must hash 123456 again with Bo’s salt, again with Cy’s, and so on. Precomputed tables of hashes (such as rainbow tables) also become useless, because nobody could have built them for your random salts.

A salt alone does not save a fast hash. Salted SHA-256 still lets an attacker try billions of guesses per second against each user; it only stops them sharing the work.

05 Slow on purpose

The other fix is to make each guess expensive. Password hashing functions such as Argon2id, scrypt and bcrypt have a cost setting. You tune it so one hash takes a fraction of a second on your server: invisible to a user signing in once, ruinous for someone trying billions of guesses.

SHA-256Billions / sRoughly what one modern GPU manages. A list of a million common passwords takes well under a second per user.
bcrypt, cost 12About a thousand / sEach hash repeats an expensive setup 2^12 times. Public GPU benchmarks put one card around this rate.
Argon2id or scryptMemory per guessEach guess also needs a large block of memory, which limits how many a GPU can run side by side.
Minimum settings from the OWASP Password Storage Cheat Sheet (check it for current values)
AlgorithmSettingsNotes
Argon2idm=19 MiB, t=2, p=1The first choice when your platform has it.
scryptN=2^17, r=8, p=1Built into Node and Python.
bcryptcost 10 or moreUses only the first 72 bytes of the password.
PBKDF2-HMAC-SHA256600,000 iterationsWhen you need a FIPS-approved algorithm.

06 What happens at sign-in

The stored value is one string that carries everything needed to check a password later: which algorithm, which cost settings, the salt, and the hash. Here is the server checking Bo’s sign-in against the string the code below produced.

Checking a sign-in against a stored scrypt hash
Step 1 of 6
Bo’s stored string, split on $
scrypt
131072
8
1
kKz97gL2…
AF+xhB5S…
What the server works out
Empty
  • reading now
  • just worked out
  • hashes match
  • not read yet

Bo types 123456 and presses sign in. The server loads the one string it stored for him. Nothing is read from it yet.

07 Try it in Node

Node ships scrypt in node:crypto, so this runs with no packages. hashPassword is called at sign-up, verifyPassword at sign-in.

passwords.js
const { randomBytes, scrypt, timingSafeEqual } = require('node:crypto');
const { promisify } = require('node:util');
const scryptAsync = promisify(scrypt);
const N = 2 ** 17; // cost: CPU and memory
const r = 8;
const p = 1;
const maxmem = 256 * N * r; // scrypt needs 128 * N * r bytes; leave room
async function hashPassword(password) {
const salt = randomBytes(16);
const hash = await scryptAsync(password, salt, 32, { N, r, p, maxmem });
return `scrypt$${N}$${r}$${p}$${salt.toString('base64')}$${hash.toString('base64')}`;
}
async function verifyPassword(password, stored) {

Hash the same password twice and check it, to see the salt at work:

try.js
const { hashPassword, verifyPassword } = require('./passwords');
(async () => {
const a = await hashPassword('123456');
const b = await hashPassword('123456');
console.log(a);
console.log(b);
console.log("verify '123456':", await verifyPassword('123456', a));
console.log("verify '1234567':", await verifyPassword('1234567', a));
})();
Shell
$ node try.js
scrypt$131072$8$1$kKz97gL2JabFDYxR7A0b6A==$AF+xhB5S1DgtMtX7RkBEj+Tx4IOMpBMYD2A1uCK5g5M=
scrypt$131072$8$1$M3MW6GROOujfFgzcEvMg8A==$PKkKkj31vf2uQJrY6/zzHpX+yIARSpVUGSidxxJJOyw=
verify '123456': true
verify '1234567': false

Your strings will differ from these, because the salts are random. The two lines also differ from each other, even though the password is the same. In a real app you would more often use a library such as argon2 or bcrypt; they produce the same kind of self-describing string and do the constant-time compare for you.

08 When it goes wrong

sha256(salt + password)A fast hash, even saltedThe salt stops shared work but not cheap guesses. Use a password hashing function with a cost setting.
stored === computedA plain string compareAn ordinary compare can stop at the first differing byte, which leaks timing. Use timingSafeEqual or the library’s own verify function.
bcrypt.hash(longPassphrase, 12)bcrypt’s 72-byte limitbcrypt uses only the first 72 bytes of input; many libraries drop the rest without telling you. Prefer Argon2id, or reject longer inputs.
md5(password)Old hashes left in placeWhen moving off a weak hash, re-hash with the new scheme the next time each user signs in, or wrap the old hash now (argon2(md5)) so no row stays weak.
cost: 12 in 2019A cost that never changesHardware gets faster. Because the settings live in each stored string, you can raise them and re-hash at the next sign-in.
POST /login × 10,000No limit on sign-in attemptsA slow hash protects a stolen table. Guessing through your login form needs rate limits and lockouts too.

Do not invent your own scheme. Pick Argon2id, scrypt or bcrypt from a maintained library, store the full string it returns, and check passwords only with its verify function.

09 Check yourself

Question

Bo and Cy both choose 123456. Each has a random salt. Their stored hashes are:

Question

Why is salted SHA-256 a poor way to store passwords?

Question

At sign-in, where does the server get the user’s salt?

10 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?