Hashing passwords

Topic 1 of 4 in Authentication & security7 min readIntermediateFree course

Overview

Every few months another company announces that its user database was stolen. What happens next depends entirely on one decision its developers made years earlier: how they stored passwords.

If they stored them as plain text, every account is compromised immediately — and because people reuse passwords, so are their email, bank and social accounts. If they stored them properly hashed, the attackers get a list of values that are extremely expensive to reverse.

This topic shows you how to do it properly using only Node’s built-in crypto module.

Hashing, not encryption

A hash function turns any input into a fixed-size fingerprint, and it only works one way: you can’t turn the hash back into the password. To check a login, you hash what the user typed and compare it with the stored hash.

Encryption is two-way — with the key, you can decrypt. That’s wrong for passwords: if attackers steal the key along with the database, they get every password. You never need to know a user’s password, only whether they typed the same one again.

Why not SHA-256?

General-purpose hashes like SHA-256 are designed to be fast — a modern graphics card computes billions per second. That’s great for checking downloads, and terrible for passwords: an attacker can try every common password, and every 8-character combination, very quickly.

Password-hashing functions are deliberately slow and memory-hungry, tunable so each guess costs real time and RAM:

Function Notes
Argon2id the current recommendation; via the argon2 npm package
scrypt built into Node (crypto.scrypt); strong and dependency-free
bcrypt very widely used; via bcrypt or bcryptjs; limits passwords to 72 bytes

This course uses scrypt because it needs no extra packages. Any of the three is a good choice.

Salt

If two users choose the same password, a plain hash would be identical — and attackers could use giant precomputed tables of common passwords’ hashes. A salt is a random value generated per user and mixed into the hash. Same password, different salt, completely different hash. The salt isn’t secret; you store it next to the hash.

Sign up: the password plus a random 16-byte salt goes through scrypt or Argon2, which is deliberately slow, and is stored in the database as scrypt$salt$hash. Log in: the typed password with the same salt read from the database goes through the same scrypt settings, and timingSafeEqual checks whether the hashes match. The password itself is never stored.

Hashing with scrypt

JavaScript
// src/auth/passwords.js
import { scrypt, randomBytes, timingSafeEqual } from 'node:crypto';
import { promisify } from 'node:util';

const scryptAsync = promisify(scrypt);
const KEY_LENGTH = 64;

export async function hashPassword(password) {
  const salt = randomBytes(16);
  const hash = await scryptAsync(password.normalize('NFKC'), salt, KEY_LENGTH);
  return `scrypt$${salt.toString('base64url')}$${hash.toString('base64url')}`;
}

export async function verifyPassword(password, stored) {
  const [scheme, saltText, hashText] = stored.split('$');
  if (scheme !== 'scrypt') return false;
  const expected = Buffer.from(hashText, 'base64url');
  const actual = await scryptAsync(password.normalize('NFKC'), Buffer.from(saltText, 'base64url'), expected.length);
  return timingSafeEqual(actual, expected);
}

A few details worth noticing:

  • Async scrypt runs in libuv’s thread pool, so hashing doesn’t block the event loop. Never use scryptSync in a server.
  • The stored string includes the scheme and salt, so you can verify it later and even upgrade the algorithm in future (argon2id$…) without breaking old accounts.
  • normalize('NFKC') makes sure the same password typed on different devices produces the same bytes (some characters have several Unicode forms).
  • timingSafeEqual compares in constant time, so response timings don’t leak how many bytes matched.

Sign-up and log-in

JavaScript
// src/auth/auth.service.js
import { hashPassword, verifyPassword } from './passwords.js';
import { HttpError } from '../errors.js';

export function makeAuthService({ usersRepo }) {
  return {
    async register({ email, password, name }) {
      const passwordHash = await hashPassword(password);
      try {
        return await usersRepo.insert({ email, name, passwordHash });
      } catch (err) {
        if (err.code === '23505') throw new HttpError(409, 'An account with this email already exists');
        throw err;
      }
    },

    async login({ email, password }) {
      const user = await usersRepo.findByEmail(email);
      const ok = user && (await verifyPassword(password, user.passwordHash));
      if (!ok) throw new HttpError(401, 'Incorrect email or password');
      return user;
    },
  };
}

Notice the login error: the same message whether the email doesn’t exist or the password is wrong. A different message (“no such user”) would let attackers discover which emails have accounts.

Never return the hash. Make sure passwordHash is stripped from every response — the repository’s mapping function is a good place to leave it out by default.

Password rules that help

Modern guidance (such as NIST’s) favours length over complexity:

  • Require at least 12 characters; allow long passphrases (at least 64 characters).
  • Don’t force symbols and digits — they lead to Password1!.
  • Reject passwords found in breach lists (services such as “Have I Been Pwned” offer a privacy-preserving check).
  • Don’t force regular password changes unless there’s evidence of compromise.
JavaScript
const registerSchema = z.object({
  email: z.email().toLowerCase(),
  name: z.string().trim().min(1).max(100),
  password: z.string().min(12, 'Use at least 12 characters').max(128),
});

Protecting the login endpoint

Slow hashing makes each guess expensive, but you should also stop attackers guessing at all:

  • Rate-limit login attempts per IP address and per account (see Securing your API).
  • Lock or slow down an account after many failures, and notify the user.
  • Offer multi-factor authentication (one-time codes, passkeys) for sensitive apps.

Tuning the cost

scrypt accepts options (N, r, p) that set how much CPU and memory each hash uses. Node’s defaults are reasonable; the goal is that hashing takes tens of milliseconds on your server — slow enough to hurt attackers, fast enough that logins feel instant. Measure on your production hardware, and remember that hashing on every login uses the thread pool.

Even better: don’t store passwords at all. “Sign in with Google/GitHub/Apple” (OAuth/OpenID Connect), magic email links and passkeys let you avoid passwords entirely. Many apps offer them alongside a password option.

Exercise

Hash and verify

Write hashPassword(password) that returns a string scrypt$<salt>$<hash> (both base64url), and verifyPassword(password, stored) that returns true or false. Use a random 16-byte salt, a 64-byte key and timingSafeEqual. Check that two hashes of the same password differ but both verify.

JavaScript
import { scrypt, randomBytes, timingSafeEqual } from 'node:crypto';
import { promisify } from 'node:util';

const scryptAsync = promisify(scrypt);

export async function hashPassword(password) {}
export async function verifyPassword(password, stored) {}

Summary

  • Never store passwords — store a slow, salted hash of them.
  • Use a password-hashing function (scrypt, Argon2id or bcrypt), never a fast hash like SHA-256 on its own.
  • A unique random salt per user makes identical passwords hash differently and defeats precomputed tables.
  • Compare hashes with timingSafeEqual, and give the same error for unknown emails and wrong passwords.
  • Require long passwords rather than complex rules, and rate-limit login attempts.