Storing Passwords Safely: Hashing

An app never keeps a password itself; it keeps a bcrypt hash, a one-way fingerprint made with a random salt and a slow cost factor, and it checks each sign-in with bcryptjs's compare.

Journeyman · Node.js · Web Development · Updated

By

After this lesson you can

  • Explain why an app stores a password's hash instead of the password, and how hashing differs from encrypting
  • Hash a password with bcryptjs hash and a cost factor, and check a sign-in attempt with compare
  • Explain what a salt and a slow cost factor protect against, and why argon2 is the stronger choice

Key takeaways

  • An app never stores a password. If the database leaks, stored passwords also open the other sites where people reused them.
  • Encrypting can be undone by anyone who has the key. Hashing is one way, and an app only ever needs to check a password, never read it back.
  • A salt is random text mixed in before hashing, so the same password gives a different hash every time and ready-made tables of hashes are no help.
  • bcrypt.hash(password, 10) makes a salted hash to save, and bcrypt.compare(attempt, hash) answers true or false at sign-in.
  • The cost factor makes hashing slow on purpose, and each step up doubles the time. argon2 is the stronger, newer choice.

The first time an app you build has a sign-up form, a password arrives at your server as plain text. What your code does with it in the next line decides how bad the worst day is: the day someone gets a copy of your database. This lesson is that line, and you'll write it in every app with accounts.

This chapter's example is Bright Minds Study Group, where students sign up, sign in and see their own study sessions. Its first student, Maya, is about to sign up.

Why the password never goes in the database

The first try is to save what Maya typed: { name: "Maya", email: "maya@example.com", password: "maya-example-password" }. Sign-in would work: compare what she types with what's saved.

It breaks on the day the data gets out, and that happens to careful teams too: a backup left on a shared drive, a copy of the database made for testing, a log line that printed a request, a stolen laptop. Whoever reads that copy reads every password. Many people use one password on several sites, so a leak of the study group's passwords opens their email too.

The second try is to encrypt it. Encryption scrambles data with a key, and the same key unscrambles it. That moves the problem: the key has to live on the server, so whoever gets the database and the key gets every password back. And an app never needs to read a password back. At sign-in it only needs to answer one question: is this the same password as last time?

Hashing: a fingerprint of the password

A fingerprint tells you whether it's the same person, but you can't rebuild the person from it. Hashing does that for data: a hash function turns any text into a fixed-size fingerprint, its hash, and there's no way to run it backward. The same text always gives the same hash, so to check a sign-in, you hash what was typed and compare the two hashes. In a security class, this is a one-way function or a cryptographic hash function.

Node.js has hash functions built in. SHA-256 (read "S-H-A two fifty-six") is one:

import { createHash } from "node:crypto";

function sha256(text) {
  return createHash("sha256").update(text).digest("hex");
}

console.log(sha256("maya-example-password"));
console.log(sha256("maya-example-password"));
console.log(sha256("maya-example-passwore"));
06cd790f366f27d430991cc94614c3d800ca9d3037b663a27fd4d8f21fd9f2e9
06cd790f366f27d430991cc94614c3d800ca9d3037b663a27fd4d8f21fd9f2e9
767405f90cdde903e110caa0b36118e2f50157a685a9ed84ed438023edc89769

Change one letter and the hash is unrecognizable. But SHA-256 was built to be fast, for checking files, and fast is wrong here. With a stolen list of fast hashes, an attacker's computer can hash billions of likely passwords a second until one matches. And the same password always gives the same hash, so attackers keep ready-made tables of the hashes of common passwords, and two students with the same password show up as twins.

bcrypt: a salt and a slow recipe

A password hash fixes both problems:

  • A salt is random text mixed in with the password before hashing, made fresh for every password. The same password gets a different hash each time, so ready-made tables are useless.
  • A cost factor makes hashing slow on purpose: too slow for billions of guesses, quick enough for one sign-in.

bcrypt (read "B-crypt") is a password hash with both. The bcryptjs package is bcrypt written in plain JavaScript, so it installs on any computer with no extra build tools. In a folder whose package.json holds { "type": "module" }, run npm install bcryptjs@3.0.3, then hash Maya's password twice:

import bcrypt from "bcryptjs";

const first = await bcrypt.hash("maya-example-password", 10);
const second = await bcrypt.hash("maya-example-password", 10);

console.log(first);
console.log(second);
$2b$10$fS01wSLf2vxahmS/7FSJmeEf8HUX4ie5bLsIxz8ioTcHJfYrczy4q
$2b$10$poasHDaV6EvFvKpf0wdaTOMJu.eP8X/Y5rr2FG8FCLWyCQiGmuqTC

One password, two different hashes, and both are right. Your run prints two others, since every salt is new. Each hash carries what's needed to check it later:

Part In the first hash What it is
Between the first two $ 2b The version of bcrypt
The number after it 10 The cost factor
The next 22 characters fS01wSLf2vxahmS/7FSJme The salt
The last 31 characters Ef8HUX4ie5bLsIxz8ioTcHJfYrczy4q The hash itself

Checking a sign-in with compare

At sign-in, bcrypt.compare takes what was typed and the saved hash. It reads the salt and the cost out of the hash, hashes the attempt the same way, and answers true or false:

import bcrypt from "bcryptjs";

const saved = await bcrypt.hash("maya-example-password", 10);

console.log(await bcrypt.compare("maya-example-password", saved));
console.log(await bcrypt.compare("Maya-example-password", saved));
true
false

One capital letter makes a different password. The password itself lives only in memory while the request runs: it's never saved and never logged, so a sign-up route never does console.log(req.body). One honest limit: bcrypt reads only a password's first 72 bytes, and bcryptjs's bcrypt.truncates(password) tells you when one is longer.

The cost factor, and argon2

The cost factor is a power of two: cost 10 means 2¹⁰ (read "two to the tenth"), 1,024 rounds, and each step up doubles the time. On the computer this lesson was written on, cost 10 took about 50 milliseconds and cost 12 about 200. One sign-in never notices 50 milliseconds, but every guess an attacker makes now costs the same. 10 is a common starting point, and this course uses it; raise it as computers get faster.

argon2 (read "AR-gon two") is the stronger, newer choice. It won the Password Hashing Competition in 2015, and it's slow in memory as well as in time, so the special hardware attackers use helps much less. Its npm package, argon2, has a compiled part that can need build tools to install, which is why this course uses bcryptjs, which runs anywhere. Both are sound choices; a fast hash, or no hash at all, is not.

Check yourself

2 questions to try on the lesson page.

So what

Somewhere, someday, a database leaks; with bcrypt hashes in it, it doesn't hand over anyone's password, and that protection is one line of your code: bcrypt.hash.

Key terms

Related