15 min read
How to store passwords in a database: hashing
In one sentence: A password is never stored, neither as it is nor encrypted: its hash is stored, computed with an algorithm that is slow on purpose (argon2id) and with a random salt for each person. To check it, the computation is repeated and compared. If someone steals the table, every guess costs them time and memory.
What you will learn
- Explain why a password is not stored in plain text, nor encrypted, nor with a fast hash like SHA-256.
- Explain what the salt does and why a password hash has to be slow.
- Store and check passwords with argon2id in Node, and read the stored text, piece by piece.
- Apply NIST's rules for passwords: length and a list of common passwords, with no required symbols and no expiry.
Before you start, read: 00-introduction.md
The problem
Section titled “The problem”Imagine that, a year from now, someone walks off with a copy of the shop’s database: a forgotten backup in a public place, a stolen laptop, or a SQL injectionSQL stands for Structured Query Language.An attack that sends a value crafted so that, pasted inside the text of a query, it changes what the query does, such as returning every row or deleting a table. It’s prevented by sending the values separately, as parameters, and never pasting them into the SQL.Go to definition like the one in Phase 5.
Marta is in the table, with her email address and her password. And Marta, like almost everyone, uses the same password for her email. With that row, whoever has it gets into her email, and from there asks for “I forgot my password” on all her other accounts.
The shop needs to check Marta’s password every time she signs in. How does it store it so it can check it, without anyone being able to read it, not even you?
The analogy
Section titled “The analogy”The analogy
Think of a smoothie. A banana, two strawberries and milk make a smoothie of a particular color and taste, and the same ingredients always make it the same. But from the smoothie you can’t get back to the fruit.
The shop doesn’t keep your fruit: it keeps your smoothie. When you come back, it blends what you bring and compares the color and the taste. If they match, it was your fruit.
So that nobody can prepare the smoothies of the most common fruits in advance, it adds to each one a pinch of a different spice, written on your glass. And it uses a blender that takes a while and fills the whole counter: for you it’s a short wait; for whoever tries millions of fruits, an endless one.
Where the analogy breaks down
- Two smoothies made from almost the same fruit look alike. Two almost identical passwords give hashes that look nothing alike.
- The spice isn’t secret: it’s written on the glass. What it achieves is that every glass is different.
- Whoever steals the table doesn’t separate the fruit: they try fruits until a smoothie matches. That’s what the slow blender is for.
How it really works
Section titled “How it really works”Storing it as it is: one leak shows them all
Section titled “Storing it as it is: one leak shows them all”If the table stores Marta’s password in plain text, the first leak shows them all. And not only in the shop: since many people reuse passwords, whoever has the list tries it on other services with the same email. It’s called credential stuffing, and programs do it, by the million. Nobody on the inside should read them either: not you, and not your LogA text file where a program writes down what happens, one line for each thing. A web server’s has a line for each request it receives, and it’s the first thing you look at when something fails.Go to definition.
Encrypting it: whoever has the key has them all
Section titled “Encrypting it: whoever has the key has them all”EncryptionTransforming a message with a key so that only someone with the key to decrypt it can read it. If the same key encrypts and decrypts, it is symmetric; if there are two different keys, a public one and a private one, it is asymmetric.Go to definition, as in Phase 0’s TLS lesson, looks like the solution, but encryption can be undone: that’s its whole point. Whoever has the key has every password at once.
And the key has to be on the server, which uses it: whoever walks off with a copy of the server usually takes the .env with it.
But the shop never needs to read Marta’s password: only to check that today’s is the usual one. For that, something that can’t be undone is enough.
A hash: checking it without being able to read it
Section titled “A hash: checking it without being able to read it”That’s what a HashA short, fixed-size summary calculated from some data, like a fingerprint. The same data always gives the same hash, and the smallest change gives a completely different one. Git calls each commit by its hash.Go to definition is: the fingerprint of some data, which can’t be undone, as you saw in “Git internals”. The shop stores the hash of the password, and to check it, it computes the hash of the one that arrives and compares.
But not just any hash will do. Look at the one for 123456, the most used password in the world, with SHA-256, the most common hash formula:
The SHA-256 of 123456
printf '%s' '123456' | shasum -a 256What you will see:
8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92 -printf '%s' writes the text without a line break at the end, which would change the hash, and shasum -a 256 computes its SHA-256. The - at the end means the text came through the PipeThe terminal’s | symbol: it connects two programs, so what the first one writes reaches the second one as input.Go to definition, not from a file. On Linux and WSL, sha256sum does the same.
Search for that hash on the internet: you’ll see it’s 123456.
SHA-256 is too fast
Section titled “SHA-256 is too fast”That hash has two problems.
The first: the same password always gives the same hash. If Carmen and Pablo use 123456, their rows have the same text, and guessing one guesses both. Worse: there are precomputed tables with the hashes of billions of passwords, ready to be searched (rainbow tables are a compact way of storing them).
The second: SHA-256 is fast. It’s made to summarize huge files in an instant, and here fast helps whoever attacks. Whoever steals the table doesn’t undo any hash: they try passwords, one after another, and compare. A gaming graphics card computes billions of SHA-256 hashes per second.
In 2012, the hashes of about 6.5 million LinkedIn passwords leaked, computed without a salt: with precomputed tables, many were guessed quickly.
Trying passwords against accounts or hashes that aren’t yours, without permission, is a crime. In this lesson, everything is done against your shop, on localhost.
The salt: the same password, two different hashes
Section titled “The salt: the same password, two different hashes”The Salt (in passwords)A random piece of data, different for each password, that’s mixed with it before calculating its hash and stored next to it. It makes the same password give different hashes, and it makes tables of already calculated hashes useless.Go to definition fixes the first problem. It’s 16 random bytes, different for each password, mixed with it before computing the hash, and stored next to it.
- Carmen and Pablo, with the same password, have different hashes, because their salts are different.
- Precomputed tables stop being useful: you’d need one for each possible salt.
The salt isn’t secret. And it doesn’t fix the second problem: whoever attacks Marta tries with Marta’s salt, just as fast.
Slow on purpose: argon2id, bcrypt and scrypt
Section titled “Slow on purpose: argon2id, bcrypt and scrypt”That’s what Password hashingStoring a password as its hash, calculated with a deliberately slow algorithm and with a salt, instead of the password itself. To check it, the calculation is repeated with what the person types and the two results are compared; the password can’t be recovered from what’s stored.Go to definition algorithms are for: slow on purpose, with adjustable slowness. Whoever signs in waits a few tens of milliseconds and doesn’t notice. Whoever tries a billion passwords waits a billion times longer.
| Algorithm | Since | What makes it expensive | OWASP’s minimum |
|---|---|---|---|
| argon2id | 2015 | Time and memory | 19 MiB of memory, 2 passes, parallelism 1 |
| scrypt | 2009 | Time and memory | N = 2¹⁷, r = 8, p = 1 |
| bcrypt | 1999 | Time | Cost 10; it only reads the first 72 bytes |
| PBKDF2 | 2000 | Time (repetitions) | 600,000 iterations with SHA-256; only if a standard requires it |
argon2id is the first choice of OWASPOWASP stands for Open Worldwide Application Security Project.An open community, backed by a nonprofit foundation, that publishes free guides and tools for building secure web applications. Its best-known document is the OWASP Top 10, the list of the ten most serious risks for web applications.Go to definition, the web security community of lesson 9. argon2, its family, won a public password algorithm competition in 2015. PBKDF2, a hash repeated thousands of times, is the one you used in the event loop lesson of Phase 3.
Memory is the key. A graphics card has thousands of small cores, but little memory for each one. If every attempt needs 19 MiB, the memory runs out long before the cores do.
argon2id in Node, without installing anything
Section titled “argon2id in Node, without installing anything”Node has included argon2 since version 24.7, in node:crypto. The shop’s parameters, in src/passwords.ts:
// argon2id with the minimum OWASP recommends (Password Storage Cheat Sheet): 19 MiB of memory,// 2 passes and 1 thread. It's slow on purpose: about 20 or 40 ms per hash. Whoever signs in doesn't// notice; for whoever tries a billion passwords, it's years. And it needs memory, which is what// costs the most for a graphics card that tries thousands at once.// crypto.argon2 has shipped with Node since version 24.7, and Node 26's documentation no longer// marks it experimental. On an older Node, the alternative is the @node-rs/argon2 package.const PARAMETERS = { memory: 19_456, // in KiB: 19 MiB passes: 2, parallelism: 1, tagLength: 32, // the hash: 32 bytes};const SALT_BYTES = 16;
// argon2 reports back with a callback, like Node's old functions. promisify turns it into one// that returns a promise, to use it with await.const compute = promisify(argon2);memory: 19_456: the memory, in blocks of 1 KiB: 19 MiB. The_only separates the digits.passes: 2: how many passes it makes over that memory.parallelism: 1: how many parts it splits the work into, which could be computed at the same time.tagLength: 32: the hash comes out at 32 bytes.promisify(argon2):argon2reports back when it’s done by calling a FunctionA named piece of code that takes some data, does something with it and returns a result. It’s written once and used as many times as needed.Go to definition you pass it;promisifyturns it into one that returns a PromiseA value that isn’t there yet but will arrive, like the text of a file that is being read. Until it arrives, the program can go on with other things; with await, it waits for it.Go to definition, so you can useawait. It computes in a helper thread, and the server keeps serving everyone else.
crypto.argon2 arrived as experimental, and the Node 26 documentation no longer marks it that way. The project uses Node 26. With an older Node, the @node-rs/argon2 package does the same, with argon2 already compiled for each system.
The PHC format: everything needed in one text
Section titled “The PHC format: everything needed in one text”hashPassword computes the hash and stores everything in a single text:
// Before anything else, normalize('NFKC'): é can be written as a single letter or as an e plus an// accent, depending on the keyboard. Normalized, the same password always gives the same bytes.// The salt: 16 random bytes, different in each hash. With it, two people with the same password// have different hashes, and a table of precomputed hashes (a rainbow table) is no use at all.export async function hashPassword(password: string): Promise<string> { const salt = randomBytes(SALT_BYTES); const hash = await compute('argon2id', { ...PARAMETERS, message: password.normalize('NFKC'), nonce: salt, }); // The PHC format: the algorithm, its version, the parameters, the salt and the hash, separated by // $. With all that in the same text, verifyPassword() knows how to repeat the computation, even if // tomorrow the parameters go up for new passwords. const { memory: m, passes: t, parallelism: p } = PARAMETERS; return `$argon2id$v=19$m=${m},t=${t},p=${p}$${toBase64(salt)}$${toBase64(hash)}`;}
// PHC uses base64 without the padding (=) at the end.const toBase64 = (bytes: Buffer) => bytes.toString('base64').replace(/=+$/, '');randomBytes(SALT_BYTES): the salt, 16 random bytes, new in every call.normalize('NFKC'):écan be written as a single letter or as aneplus an accent. Normalized, the same password always gives the same bytes.- The
returnjoins everything with$, in the PHC format, the one almost every argon2 library uses.
Marta’s, which you’ll create in “Try it,” piece by piece:
$argon2id$v=19$m=19456,t=2,p=1$p0YG0BI1Ezmt3sR0j6EO9g$xmgmXcaLwoY/GWPRpQVbNaC/bc4XeVdq5g1aCnRYMtc| Piece | What it is |
|---|---|
argon2id |
The algorithm |
v=19 |
The argon2 version, 1.3: it’s written 0x13 in hexadecimal, which is 19 |
m=19456,t=2,p=1 |
Memory, passes and threads |
p0YG0BI1Ezmt3sR0j6EO9g |
The salt: 16 bytes in base64, without the = padding |
xmgmXcaLwoY/…nRYMtc |
The hash: 32 bytes in base64 |
With the parameters inside, tomorrow you can raise them for new passwords, and the old ones are checked with their own. An old one can only be updated when its owner signs in: it’s the only moment the shop has the password.
Checking: the same computation and a constant-time comparison
Section titled “Checking: the same computation and a constant-time comparison”// Repeats the computation with the stored salt and parameters, and compares. timingSafeEqual takes// the same time whether it matches or not (Phase 4, the webhooks' signature).export async function verifyPassword(password: string, stored: string): Promise<boolean> { const [, algorithm, version, parameters, salt, hash] = stored.split('$'); const numbers = /^m=(\d+),t=(\d+),p=(\d+)$/.exec(parameters ?? ''); if (algorithm !== 'argon2id' || version !== 'v=19' || !numbers || !salt || !hash) return false; const expected = Buffer.from(hash, 'base64'); const computed = await compute('argon2id', { memory: Number(numbers[1]), passes: Number(numbers[2]), parallelism: Number(numbers[3]), tagLength: expected.length, message: password.normalize('NFKC'), nonce: Buffer.from(salt, 'base64'), }); return timingSafeEqual(computed, expected);}stored.split('$')separates the pieces, and the computation is the one inhashPassword, with the stored salt and parameters.timingSafeEqualcompares taking the same time whether it matches or not, like the webhooks’ signature in Phase 4. A normal comparison stops at the first different byte, and by measuring how long it takes, someone can work out the result bit by bit.
The rules that help and the ones that don’t
Section titled “The rules that help and the ones that don’t”The usual rules, “one capital letter, one number and one symbol, and change it every three months,” push people to Password1!, then to Password2!, and to a sticky note. NIST, the United States standards institute, withdrew them in its SP 800-63B-4 guide, from 2025:
| Helps | Doesn’t help |
|---|---|
| A minimum of 15 characters if the password is used on its own, without a second factor: a sentence will do | Requiring capital letters, numbers or symbols (NIST forbids it) |
| Accepting at least 64, with spaces, accents and emojis | A short maximum, like 16 |
| Rejecting common, leaked or predictable passwords, and saying why | Changing it every so often: only if there are signs it has leaked |
| Allowing pasting and password managers | Hints and security questions (“your first pet?”) |
In the shop:
// NIST's rules (SP 800-63B-4): a minimum length and a list of known passwords. None of "one// capital, one number and one symbol", nor changing it every three months: with those rules people// end up with Password1! and Password2!, easy to guess.const MIN_LENGTH = 15; // NIST: 15 for a password used on its own, without a second factorconst MAX_LENGTH = 128; // a generous cap: NIST asks to accept at least 64
// The common passwords, in lowercase, in a Set: looking something up in it is instant. Lines that// start with # are the file's comments.const COMMON = new Set( readFileSync(new URL('common-passwords.txt', import.meta.url), 'utf8') .split('\n') .filter((line) => line !== '' && !line.startsWith('#')) .map((line) => line.toLowerCase()),);
// Returns what's wrong with the password, or undefined if it's fine. The length is counted in// characters: [...text] separates emojis and unusual letters, which in JavaScript take up two// "letters" of length.export function passwordProblem(password: string): string | undefined { const characters = [...password.normalize('NFKC')].length; if (characters < MIN_LENGTH) return `At least ${MIN_LENGTH} characters: a sentence will do`; if (characters > MAX_LENGTH) return `At most ${MAX_LENGTH} characters`; if (COMMON.has(password.toLowerCase())) { return "It's one of the most used passwords: it's the first thing anyone tries"; } return undefined;}MIN_LENGTHandMAX_LENGTH: from 15 to 128 characters.COMMONreadssrc/common-passwords.txt: the ones with 15 characters or more that are a pattern (keyboard rows, digits in a row) among the 100,000 most used, a list from the UK’s National Cyber Security Centre. WithtoLowerCase(),QWERTY…andqwerty…count the same.[...password.normalize('NFKC')].lengthcounts real characters: forlength, an emoji takes up two.
A real shop would check many more, for example with Pwned Passwords, a service that tells you whether a password has appeared in a leak without you sending it the password.
The users table and POST /v2/accounts
Section titled “The users table and POST /v2/accounts”Accounts live in a new table, with its MigrationA file with a change to a database’s tables, such as adding a column, that is applied only once and in order, without deleting the data already there. The database itself records in a table which ones have already been applied.Go to definition, number 005:
CREATE TABLE users ( id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY, email text NOT NULL, -- The password's hash, with its salt and its parameters: $argon2id$v=19$m=19456,t=2,p=1$… -- It can be missing (NULL): whoever comes in with an identity provider (lesson 4) has no -- password in the shop. password_hash text, created_at timestamptz NOT NULL DEFAULT now());
-- One email, one account, whatever the capitals: Ana@Shop.example and ana@shop.example are the-- same person. The index is on lower(email), so PostgreSQL compares both in lowercase, and it also-- serves to find an account by its email when signing in.CREATE UNIQUE INDEX users_email_unique ON users (lower(email));password_hashcan be missing: whoever comes in with another account, like “Sign in with Google” (lesson 4), has no password in the shop.- The unique index on
lower(email):Marta@Example.comandmarta@example.comare the same account.
createUser, in src/users.ts, computes the hash and saves the row. If the email already exists, PostgreSQL answers 23505 and the function returns email-taken. A SELECT beforehand wouldn’t be enough: two sign-ups at once would both pass it, Phase 5’s race condition.
The route, in src/v2.ts:
// By the time it gets here, the email has the shape of an email and the password meets the rules// (the schema). The response carries the id and the email: the hash never leaves the database.v2.openapi(contract.createAccount, async (c) => { const { email, password } = c.req.valid('json'); const result = await createUser(email, password); if ('error' in result) { // Saying "that email already has an account" tells anyone who is a customer of the shop. To // not say it, the response would always be the same and the shop would send an email to the // address; there's no email here, so it's said, and lesson 8 limits how many times you can ask. return problem(c, { type: problemType('email-taken'), title: 'There is already an account with that email', status: 409, detail: 'If it is yours, sign in with it', }); } const { user } = result; // The new account's URL. The API doesn't have a route to read it yet: each person will see // theirs at /v2/me (lesson 2). return c.json(user, 201, { Location: `${c.req.path}/${user.id}` });});- The rules are checked first: the
newAccountSchemaschema, insrc/schemas.ts, callspasswordProblem, and if it fails it answers422, like all ValidationChecking, every time it arrives, that the data the client sends is what was expected before using it: that no field is missing, that a number is a number and that it’s within what’s allowed. If something doesn’t match, the server answers with an error and stops there.Go to definition since Phase 3. - A repeated email is a
409, with Problem DetailsThe standard shape of the body of an error response in an API, written down in RFC 9457: a JSON with type (what kind of problem it is), title (its summary), status (the status code), detail (what happened this time) and instance (which of the times). It’s sent with the content type application/problem+json.Go to definition. - The response carries the id and the email, never the hash.
That 409 tells anyone whether an email has an account. Keeping quiet about it would require sending an email; here, lesson 8, “Rate limiting,” will limit how many times anyone can ask.
Try it
Section titled “Try it”The goal: sign Marta up, see that nobody can read her password in the table and measure how much slower argon2id is.
Update your project
Section titled “Update your project”You start from your project from lesson 9 of Phase 5, “ORM”, in ~/backend-course/phase-3/shop-api. There are no new packages: argon2 comes with Node.
- Create
src/passwords.tsandsrc/users.ts, and copy thesrc/common-passwords.txtlist from the step. - Create
db/migrations/005-users.sql. - Add the
userstable tosrc/schema.ts,newAccountSchemaanduserSchematosrc/schemas.ts, thecreateAccountroute tosrc/contract.tsand the route tosrc/v2.ts. Whatever you haven’t seen here, copy it from the step.
The example and the tests come in this lesson’s folder:
cd ~/backend-course/phase-3curl -O https://backenddesdecero.com/practicas/shop-api/24-passwords.tar.gztar -xzf 24-passwords.tar.gzcd shop-apicp ../24-passwords/examples/fast-hash.ts examples/cp ../24-passwords/db/accounts.sql db/cp ../24-passwords/scripts/seed.ts scripts/cp ../24-passwords/test/*.ts test/db/accounts.sql brings four practice accounts with their hash, and the new seed.ts loads them with npm run db:seed. The tests already use them; you will in lesson 5. If you load them before, Marta won’t be account 1.
1. drizzle-kit's snapshot
npm run db:generate -- --name=usersWhat you will see:
> shop-api@1.0.0 db:generate> drizzle-kit generate --name=users
No config path provided, using default 'drizzle.config.ts'Reading config file '/Users/ana/backend-course/phase-3/shop-api/drizzle.config.ts'7 tablescategories 2 columns 0 indexes 0 fksidempotency_keys 6 columns 0 indexes 0 fksorders 5 columns 1 indexes 1 fksprocessed_events 2 columns 0 indexes 0 fksproduct_categories 2 columns 1 indexes 2 fksproducts 4 columns 0 indexes 0 fksusers 4 columns 1 indexes 0 fks
[✓] Your SQL migration file ➜ drizzle/0002_users.sql 🚀As in lesson 9 of Phase 5. This time, 005 in db/migrations/ is written by hand, with comments, and it says the same as drizzle/0002_users.sql. If you get No schema changes, you didn’t save schema.ts.
2. Apply the migration
npm run db:migrateWhat you will see:
> shop-api@1.0.0 db:migrate> node --env-file-if-exists=.env scripts/migrate.ts
Applied: 005-users.sqlAfterwards, npm test should end with fail 0. The outputs are from Node 26.11.1 and PostgreSQL 18; your ids, hashes and times will be different.
Marta signs up
Section titled “Marta signs up”Start the API with npm start and, in another terminal:
3. A new account
curl -s -i -w '\n' --json '{"email":"marta@example.com","password":"a long sentence only I know"}' localhost:3000/v2/accountsWhat you will see:
HTTP/1.1 201 Createdcontent-type: application/jsonlocation: /v2/accounts/1vary: Originx-request-id: be793323-1a22-4965-85f9-83e5449547dacontent-length: 36Date: Wed, 14 Oct 2026 04:42:37 GMTConnection: keep-aliveKeep-Alive: timeout=5
{"id":1,"email":"marta@example.com"}A 201 with the id and the email. It’s the first account in your table: id 1.
4. The same email, with different capitals
curl -s -i -w '\n' --json '{"email":"Marta@Example.com","password":"another long different sentence"}' localhost:3000/v2/accountsWhat you will see:
HTTP/1.1 409 Conflictcontent-type: application/problem+jsonvary: Originx-request-id: 7373a3e4-9cbd-414b-ba45-9c3343cdce0econtent-length: 162Date: Wed, 14 Oct 2026 04:42:37 GMTConnection: keep-aliveKeep-Alive: timeout=5
{"type":"https://shop.example/problems/email-taken","title":"There is already an account with that email","status":409,"detail":"If it is yours, sign in with it"}The index on lower(email) sees the same account. If you get a 500, check that createUser looks at error.cause: Drizzle wraps PostgreSQL’s error.
Now Lucía tries to sign up with two bad passwords:
5. A short one and one of the most used
curl -s -w '\n' --json '{"email":"lucia@example.com","password":"Lucia2026!"}' localhost:3000/v2/accountscurl -s -w '\n' --json '{"email":"lucia@example.com","password":"1q2w3e4r5t6y7u8i9o0p"}' localhost:3000/v2/accountsWhat you will see:
{"type":"https://shop.example/problems/invalid-data","title":"The data is not valid","status":422,"detail":"See \"errors\" for what is wrong with each field.","errors":[{"field":"password","problem":"At least 15 characters: a sentence will do"}]}{"type":"https://shop.example/problems/invalid-data","title":"The data is not valid","status":422,"detail":"See \"errors\" for what is wrong with each field.","errors":[{"field":"password","problem":"It's one of the most used passwords: it's the first thing anyone tries"}]}Lucia2026! meets the usual rules, and it’s short. 1q2w3e4r5t6y7u8i9o0p has 20 characters, but it zigzags across the keyboard: it’s the first one on the list.
In the server’s terminal, ms says how long each request took: the 422s, two milliseconds at most, without computing any hash. And no line carries the body: a password never goes into a log.
What the table stores
Section titled “What the table stores”6. Marta's row
psql -d shop -c 'SELECT id, email, password_hash FROM users;'What you will see:
id | email | password_hash----+-------------------+---------------------------------------------------------------------------------------------------1 | marta@example.com | $argon2id$v=19$m=19456,t=2,p=1$p0YG0BI1Ezmt3sR0j6EO9g$xmgmXcaLwoY/GWPRpQVbNaC/bc4XeVdq5g1aCnRYMtc(1 row)That’s everything the shop knows about Marta’s password. You have full access to the database, and you can’t read it: you can only check one someone gives you, as lesson 2 will do when signing in.
Fast versus slow
Section titled “Fast versus slow”examples/fast-hash.ts computes a million SHA-256 hashes, then one argon2id, and finally the same password twice:
7. Measure both
node examples/fast-hash.tsWhat you will see:
A million SHA-256 hashes: 1455 msOne argon2id hash: 32 msIn the time one argon2id takes, SHA-256 computes about 21,998.
The same password, twice:$argon2id$v=19$m=19456,t=2,p=1$cFrwO3L+p9seBAn1uU3HJQ$398u5RWx7yzGGNE/dX9fx+g5xTXmwkCH7DPRT+wQFNg$argon2id$v=19$m=19456,t=2,p=1$P49hgCzZizshQ9bQW3qPjQ$832lsASI6axGe1Up5CEyZC0piRnPh2gE3lB3mlhSibgThe third line: for every password tried against argon2id, thousands are tried against SHA-256. Your times depend on your computer.
And in the last two: the same sentence gives two different texts, each with its own salt.
You have already seen it
Section titled “You have already seen it”- “I forgot my password.” A well-made site sends you a link to set a new one, never your password: it doesn’t have it. If one ever emails it to you, it stores it in plain text or encrypted.
- The leaked password warning from your browser or your password manager: it checks yours against known leaks.
Common mistakes
Section titled “Common mistakes”- Encrypting passwords, or converting them to base64, which isn’t even encryption: both can be undone.
- Using a fast hash, MD5, SHA-1 or SHA-256, even with a salt.
- One fixed salt for everyone, or the email as the salt. The salt is random and different in every hash.
- Comparing with
===. UsetimingSafeEqual. - Using
argon2Syncin a route: it blocks the server while it computes. - Writing the request body to the log, or returning the hash in the API.
Summary
Section titled “Summary”- A password is never stored: not in plain text, because one leak shows them all, and not encrypted, because whoever has the key has them all.
- A hash is stored, which can’t be undone. To check the password, it’s computed again and compared in constant time.
- A fast hash like SHA-256 lets attackers try billions of passwords per second. The salt, random for each one, makes precomputed tables useless.
- argon2id is slow on purpose and needs memory. The stored text (PHC) carries the algorithm, the parameters, the salt and the hash.
- NIST: 15 characters at least and a list of common passwords; no required symbols and no expiry.
Did you get it?
Section titled “Did you get it?”To review:
Further reading
Section titled “Further reading”- Password Storage Cheat Sheet (OWASP): which algorithm to use and with which parameters.
- NIST SP 800-63B-4 (NIST): the rules for passwords, in section 3.1.1.
- RFC 9106 (IETF): argon2, inside.
- crypto.argon2 and timingSafeEqual (Node.js).
- The PHC format: how a password hash is written with its parameters.
- Have I Been Pwned: check whether your email has appeared in a leak.