Design a password hasher with upgradeable parameters

Design a small password hashing class on scrypt from the standard library: a self-describing stored format, a per-hash random salt, a needsRehash check so cost can rise over the years, equal work for unknown users, and input limits that stop the hasher becoming a denial-of-service lever.

● EasyFREEBy ·Design problem·17 min read·Beginner → Intermediate
password hashingscryptsaltrehash on loginwork factorself-describing hash format

01Understand the problem

✓What you will learn
  • Explain why password storage needs a slow, memory-hard function and a unique salt
  • Store hashes in a self-describing format so parameters travel with each hash
  • Raise the work factor later with rehash on login, without knowing any password
  • Close the user enumeration timing gap and bound the cost of each request
◎Interview radar

What they probe: the difference between a hash and a password hash, what the salt is for, where parameters are stored, how you upgrade from N=2^15 to N=2^17 for a million users, and what happens on a login for a non-existent account. Where candidates slip: SHA-256 with a salt, a single global salt, parameters held only in config (so old hashes cannot be verified), a batch job that 'rehashes everyone', comparing hashes with ===.

A password database will leak one day, so design for that day. Fast hashes such as SHA-256 let a single GPU test billions of guesses per second. A password hashing function is deliberately slow and, in the case of scrypt and Argon2, memory-hard, so each guess also needs a large block of RAM. A random salt per hash means identical passwords produce different hashes and precomputed tables are useless.

  1. hash(password) returns a string containing algorithm, parameters, salt and derived key.
  2. verify(stored, password) returns whether it matches and whether the stored hash should be upgraded.
  3. Parameters are configuration; changing them affects new hashes immediately and old hashes at their next successful login.
  4. Verification for an unknown user costs the same as for a real one.
  5. Passwords longer than a fixed limit are refused before any hashing.
FunctionRecommended setting (OWASP Password Storage Cheat Sheet)Notes
Argon2idm=19 MiB, t=2, p=1 minimumFirst choice when a maintained library is available
scryptN=2^17, r=8, p=1 (128 MiB per hash)In the Node and Python standard libraries; this lesson's default
bcryptcost 10 or moreOnly the first 72 bytes of the password count
PBKDF2-HMAC-SHA256600,000 iterationsFor FIPS-140 environments; not memory-hard

02Interfaces first

The contractts
export interface ScryptParams {
  logN: number;   // N = 2 ** logN; CPU and memory cost
  r: number;      // block size; memory is about 128 * N * r bytes
  p: number;      // parallelisation
}

export interface HasherConfig {
  current: ScryptParams;     // used for every new hash
  keyLen: number;            // 32 bytes
  saltLen: number;           // 16 bytes
  maxPasswordBytes: number;  // 1024; stops multi-megabyte "passwords"
  maxConcurrent: number;     // memory budget / memory per hash
}

export type VerifyResult = { ok: false } | { ok: true; needsRehash: boolean };

export interface PasswordHasher {
  hash(password: string): Promise<string>;
  verify(stored: string | undefined, password: string): Promise<VerifyResult>;
}
Stored formattext
$scrypt$ln=17,r=8,p=1$4fJ0bS1t3NnYyoYp1x9uVQ$Jb0dQm5gU1y1o1oZzQ8wKcG2yV0x3m3V6c5Qy9YzK2E
  |       |              |                      |
  scheme  parameters     salt (base64, 16 B)    derived key (base64, 32 B)   values illustrative
iWhy the parameters live in the hash

Config only says what new hashes should use. If the parameters were only in config, raising N would make every existing hash unverifiable. With them inside each string, verify always uses the parameters that hash was made with, and needsRehash compares them with the current config.

03The hasher

ScryptHasherts
import { randomBytes, scrypt, timingSafeEqual, type ScryptOptions } from "node:crypto";

const FORMAT = /^\$scrypt\$ln=(\d{1,2}),r=(\d{1,2}),p=(\d{1,2})\$([A-Za-z0-9+/]{16,88})\$([A-Za-z0-9+/]{16,88})$/;

function scryptAsync(pw: Buffer, salt: Buffer, len: number, opts: ScryptOptions): Promise<Buffer> {
  return new Promise((resolve, reject) => scrypt(pw, salt, len, opts, (err, key) => (err ? reject(err) : resolve(key))));
}

const b64 = (b: Buffer) => b.toString("base64").replace(/=+$/, "");

function checkParams(p: ScryptParams): void {
  if (!Number.isInteger(p.logN) || p.logN < 14 || p.logN > 20) throw new RangeError("logN must be in [14, 20]");
  if (!Number.isInteger(p.r) || p.r < 1 || p.r > 16) throw new RangeError("r must be in [1, 16]");
  if (!Number.isInteger(p.p) || p.p < 1 || p.p > 4) throw new RangeError("p must be in [1, 4]");
}

const memoryBytes = (p: ScryptParams) => 128 * 2 ** p.logN * p.r;

export class ScryptHasher implements PasswordHasher {
  private active = 0;
  private dummy: Promise<string> | undefined;

  constructor(private readonly cfg: HasherConfig) {
    checkParams(cfg.current);
    if (cfg.saltLen < 16 || cfg.keyLen < 32) throw new RangeError("salt >= 16 and key >= 32 bytes");
  }

  private encodeInput(password: string): Buffer {
    const bytes = Buffer.from(password.normalize("NFC"), "utf8");   // one spelling for the same characters
    if (bytes.length === 0 || bytes.length > this.cfg.maxPasswordBytes) throw new RangeError("password length out of range");
    return bytes;
  }

  private async derive(pw: Buffer, salt: Buffer, p: ScryptParams, len: number): Promise<Buffer> {
    if (this.active >= this.cfg.maxConcurrent) throw new Error("hasher busy");     // shed load instead of exhausting memory
    this.active++;
    try {
      return await scryptAsync(pw, salt, len, { N: 2 ** p.logN, r: p.r, p: p.p, maxmem: 2 * memoryBytes(p) });
    } finally {
      this.active--;
    }
  }

  async hash(password: string): Promise<string> {
    const p = this.cfg.current;
    const salt = randomBytes(this.cfg.saltLen);
    const key = await this.derive(this.encodeInput(password), salt, p, this.cfg.keyLen);
    return "$scrypt$ln=" + p.logN + ",r=" + p.r + ",p=" + p.p + "$" + b64(salt) + "$" + b64(key);
  }

  async verify(stored: string | undefined, password: string): Promise<VerifyResult> {
    const pw = this.encodeInput(password);
    // Unknown user: hash against a fixed dummy so the response time does not reveal whether the account exists.
    const target = stored ?? (await (this.dummy ??= this.hash("dummy-password-for-timing")));
    const m = FORMAT.exec(target);
    if (!m) throw new Error("stored hash is not in the expected format");          // corrupt data is a bug, not a wrong password
    const params = { logN: Number(m[1]), r: Number(m[2]), p: Number(m[3]) };
    checkParams(params);                                                            // a tampered row must not request 64 GiB
    const salt = Buffer.from(m[4], "base64");
    const expected = Buffer.from(m[5], "base64");
    const actual = await this.derive(pw, salt, params, expected.length);
    const ok = timingSafeEqual(actual, expected) && stored !== undefined;
    if (!ok) return { ok: false };
    const c = this.cfg.current;
    const needsRehash = params.logN !== c.logN || params.r !== c.r || params.p !== c.p || expected.length !== this.cfg.keyLen;
    return { ok: true, needsRehash };
  }
}

Rehash on login is the only way to upgrade: the plaintext exists for a moment after a successful verify and never otherwise. The login handler writes the new hash with a compare-and-set on the old value, so a password change that happened in between is not overwritten.

Rehash on logints
export async function login(users: UserRepo, hasher: PasswordHasher, email: string, password: string): Promise<string | null> {
  const user = await users.findByEmail(email.trim().toLowerCase());
  const r = await hasher.verify(user?.passwordHash, password);
  if (!user || !r.ok) return null;
  if (r.needsRehash) {
    const next = await hasher.hash(password);
    await users.replaceHashIf(user.id, user.passwordHash, next);   // UPDATE ... WHERE id = ? AND password_hash = ?
  }
  return user.id;
}
▭On the whiteboard · Design choices4 points
01
format
$scrypt$ln,r,p$salt$key: every hash carries its own parameters
02
upgrade
needsRehash on successful login, written with compare-and-set
03
limits
1024-byte cap, parameter bounds on parse, concurrency cap from the memory budget
04
timing
dummy hash for unknown users; constant-time compare of the derived keys

04Edge cases and tests

Edge caseRiskHandling
Very long password1 MB input per request multiplies CPU costRefuse above 1024 bytes before hashing
Tampered row with ln=30Verify tries to allocate 128 GiBBounds check parsed parameters
50 logins at once at 128 MiB each6.4 GiB of RAM, process killedConcurrency cap; return 503 and let clients retry
Unicode spelling differencesé as one or two code points hashes differentlyNFC before hashing, consistently, from day one
Users who never log inTheir hashes keep old parameters foreverAfter a deadline, expire them and force a reset via email
Default Node maxmem32 MiB, smaller than N=2^17, r=8 needs; scrypt throwsPass maxmem explicitly, as derive does
!A pepper is a separate decision

A pepper (a secret key mixed in with HMAC, stored outside the database) helps when only the database leaks. It adds key management and rotation work; the crypto and protocol module covers it. Do not invent one by concatenating a constant string kept in the same config file as the database password.

vitestts
import { describe, it, expect } from "vitest";

const LOW = { logN: 14, r: 8, p: 1 };      // fast parameters for tests only
const HIGH = { logN: 15, r: 8, p: 1 };
const make = (current: ScryptParams) => new ScryptHasher({ current, keyLen: 32, saltLen: 16, maxPasswordBytes: 1024, maxConcurrent: 4 });

describe("ScryptHasher", () => {
  it("round-trips and salts every hash", async () => {
    const h = make(LOW);
    const a = await h.hash("correct horse");
    const b = await h.hash("correct horse");
    expect(a).not.toBe(b);
    expect(await h.verify(a, "correct horse")).toEqual({ ok: true, needsRehash: false });
    expect(await h.verify(a, "Correct horse")).toEqual({ ok: false });
  });
  it("verifies old hashes after the cost rises and asks for a rehash", async () => {
    const old = await make(LOW).hash("pw-1");
    expect(await make(HIGH).verify(old, "pw-1")).toEqual({ ok: true, needsRehash: true });
  });
  it("never accepts an unknown user, even with the dummy password", async () => {
    expect(await make(LOW).verify(undefined, "dummy-password-for-timing")).toEqual({ ok: false });
  });
  it("refuses oversized input and tampered parameters", async () => {
    const h = make(LOW);
    await expect(h.verify(undefined, "x".repeat(2000))).rejects.toThrow(RangeError);
    const evil = (await h.hash("pw")).replace("ln=14", "ln=30");
    await expect(h.verify(evil, "pw")).rejects.toThrow(/logN/);
  });
});

05Extensions, follow-ups, how to say it

  • Algorithm migration: add a second scheme prefix ($argon2id$) and route by prefix; needsRehash returns true for any scheme that is not current.
  • Python equivalent: hashlib.scrypt(pw, salt=salt, n=2**17, r=8, p=1, maxmem=256 * 2**20, dklen=32).
  • Breached password check: at set-password time, query a k-anonymity API (Have I Been Pwned range API) with the first five hex characters of the SHA-1; never at login.
  • Worker pool: move hashing to a worker thread pool sized to the memory budget so one slow hash never blocks the event loop.
Q1How do you move a million users from N=2^15 to N=2^17?+

Change config. New hashes use 2^17 at once; existing users are upgraded on their next successful login because needsRehash is true. After a deadline, users who never returned are forced through a reset.

Q2Why throw on a malformed stored hash instead of returning false?+

A malformed hash is data corruption or tampering, and returning false would hide it as a wrong password. Throwing surfaces it as an error to alert on, while the client still sees a generic failure.

Q3What does the salt not protect against?+

A targeted guess against one hash. Salt stops precomputation and makes each hash a separate job; only the slow, memory-hard function makes each guess expensive.

“How to say it in the room

"I use scrypt from the standard library at N=2^17, r=8, p=1, a 16-byte random salt and a 32-byte key, stored as a self-describing string with the parameters inside. Verify parses and bounds those parameters, derives with them, compares in constant time, and reports needsRehash when they differ from config, so a successful login upgrades the hash with compare-and-set. Unknown users get the same work against a dummy hash. Passwords over 1 KB are refused and concurrency is capped from the memory budget."

Test yourself

You raise scrypt from logN=15 to logN=17 in config. What happens to a user whose hash was made with logN=15?

Finished this one?
Tick it and it shows as done on the roadmap and the course.