Password Hashing — Auth

Store the hash, not the password, because a hash is one-way while encryption opens with a key. At register: a random salt per user, a slow hash (PBKDF2 with…

Say the School Portal database leaks tomorrow morning. If its password column holds secret123 as it is, every account is open to whoever has that file.

That's why a server never stores the password. It stores its hash: a one-way result that can be matched but never turned back into the password. It's like keeping the juice, not the fruit. Fruit turns into juice easily, juice never turns back into fruit. To check the fruit a guest brings, you blend it with the same spices and taste: the same taste means the same fruit.

Hash, not encrypt

Encryption works both ways: whoever holds the key can open the content again. If the database and the key leak together, every password is exposed. A hash works one way: there is no key that reverses it. The server doesn't need to know your real password. It just computes the hash of what you typed again and compares.

Why a fast hash like SHA-256 must not be used for passwords, and what a rainbow table is, is covered in the Password Hashing & Storage lesson of the Security track. Here we build its two moments: register and log in.

Register: make a salt, then hash

A salt is random bytes made fresh for each user and mixed into the hash. The browser has a built-in password hash in Web Crypto, PBKDF2: it runs HMAC-SHA-256 over and over, as many iterations as you ask, so every guess is expensive.

const enc = new TextEncoder();
const toB64 = (bytes) => btoa(String.fromCharCode(...bytes));

async function pbkdf2(password, salt, iterations) {
  const key = await crypto.subtle.importKey("raw", enc.encode(password), "PBKDF2", false, ["deriveBits"]);
  const bits = await crypto.subtle.deriveBits({ name: "PBKDF2", hash: "SHA-256", salt, iterations }, key, 256);
  return new Uint8Array(bits);
}

async function hashPassword(password, iterations = 600000) {
  const salt = crypto.getRandomValues(new Uint8Array(16)); // 16 random bytes, new for every user
  const hash = await pbkdf2(password, salt, iterations);
  return `pbkdf2_sha256$${iterations}$${toB64(salt)}$${toB64(hash)}`;
}

In School Portal, Siti and Mr. Andi happen to use the same password, secret123. Before you look at the table, guess: is their password_hash column the same or different? This is the users table in the Lab, under the old policy of 100,000 iterations:

User password_hash
Siti pbkdf2_sha256$100000$ej8ZxOK4DVah9MOeiyfQZQ==$JQBztyKMm652QALrAzzNP4mF26qzKYGGuXBhu3RIsxE=
Mr. Andi pbkdf2_sha256$100000$yB5dCpfyNGsOnafBXziy5A==$XqmOAVffsNjD3rjdaP8dK+wHFcKljppHDFrOPO8LZiw=

Both passwords are secret123, but the salts differ, so the hashes differ too. Someone reading this table can't tell the two people share a password.

Log in: compute again, then compare

const fromB64 = (text) => Uint8Array.from(atob(text), (c) => c.charCodeAt(0));

function timingSafeEqual(a, b) {
  if (a.length !== b.length) return false;
  let diff = 0;
  for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i]; // always checks every byte
  return diff === 0;
}

async function verifyPassword(password, stored) {
  const [algo, iterations, salt, hash] = stored.split("$");
  if (algo !== "pbkdf2_sha256") return false;
  const again = await pbkdf2(password, fromB64(salt), Number(iterations));
  return timingSafeEqual(again, fromB64(hash));
}

const siti = { password_hash: "pbkdf2_sha256$100000$ej8ZxOK4DVah9MOeiyfQZQ==$JQBztyKMm652QALrAzzNP4mF26qzKYGGuXBhu3RIsxE=" };
console.log(await verifyPassword("secret123", siti.password_hash)); // true
console.log(await verifyPassword("secret124", siti.password_hash)); // false

How many iterations, and how to raise them

OWASP recommends 600,000 iterations for PBKDF2-HMAC-SHA256. One login then takes tens to hundreds of milliseconds. One person doesn't notice, but an attacker who wants to try billions of guesses slows down by the same amount. The Lab measures the time in your browser.

When the policy rises from 100,000 to 600,000, old hashes can't be converted directly, because the real password isn't on the server. The way out: rehash on login. Right after a successful login the server is holding the correct password, so it computes a new hash (new salt, 600,000 iterations) and overwrites the old row.

In Laravel: bcrypt

On a PHP server you don't write PBKDF2 yourself. Laravel uses bcrypt by default (or argon2id, which also needs lots of memory per guess):

$hash = Hash::make('secret123');
// $2y$12$EKag4gcNV6vQnzvBWEpnHenDf2/jrEPI4Or8STd2.a9p6W9TRypKW

Hash::check('secret123', $hash);   // true
Hash::check('secret124', $hash);   // false
Hash::needsRehash($hash);           // true once the cost in the config has gone up

Why does the Lab use PBKDF2? Because that's what the browser's Web Crypto offers. The idea is the same as bcrypt and argon2id: a salt per user, and slow on purpose.

⚠️ Missteps when storing and matching hashes

TL;DR: Store the hash, not the password, because a hash is one-way while encryption opens with a key. At register: a random salt per user, a slow hash (PBKDF2 with 600,000 iterations, bcrypt or argon2id), and store the algorithm, parameters, salt and hash in one string. At login: compute again with the stored salt and parameters, compare every byte, and answer an unknown email with the same message and timing. Raise the cost by rehashing on login. In Laravel: Hash::make, Hash::check, Hash::needsRehash, and never ===.

⚡ Hash, not encrypt

Meaning: Encryption can be opened again by whoever holds the key. A hash works one way only: there is no key that turns it back into the password. The server doesn't need your real password, it just computes the hash of what you typed again and compares.

⚡ A new salt for every user

Write:

async function hashPassword(password, iterations = 600000) {
  const salt = crypto.getRandomValues(new Uint8Array(16)); // 16 random bytes, new for every user
  const hash = await pbkdf2(password, salt, iterations);
  return `pbkdf2_sha256$${iterations}$${toB64(salt)}$${toB64(hash)}`;
}
Guess first: Siti and Mr. Andi both use the password secret123. Is their password_hash column the same or different?

Different. The salts differ, so the hashes differ too. Someone reading the table can't tell the two share a password.

Meaning: What gets stored is one string of four parts, separated by $: the algorithm name, the iteration count, the salt and the hash. At login, the server needs all of them to compute it again.

⚡ Don't compare with ===

Meaning: A new hash always has a new salt, so bcrypt('secret123') twice gives two different strings. Match with Hash::check or verifyPassword, which compute again with the stored salt.

⚡ Unknown email: same message, same timing

Meaning: Answer "Email or password is wrong", the same as for a wrong password, and still run one dummy hash. Otherwise the answer for an unknown email comes back faster, and anyone can work out which emails are registered.

What you will learn