Password hashing

suggest change

Never store user passwords as plain text. Never store them encrypted either: anything you can decrypt, an attacker who steals your database and your key can decrypt too.

Instead you store a password hash: the output of a one-way function that is deliberately slow and uses a random salt. At login you run the same function on the submitted password and compare the results.

Node.js ships everything you need in node:crypto:

There are also popular npm packages: argon2 and bcrypt.

For general hashing, HMAC and encryption see Cryptography. For generating salts and tokens see Random numbers.

Why not SHA-256?

A general purpose hash like SHA-256 is the wrong tool for passwords, for two reasons:

import { createHash } from 'node:crypto';

const pw = 'hunter2';
console.log(createHash('sha256').update(pw).digest('hex'));
console.log(createHash('sha256').update(pw).digest('hex'));

const start = performance.now();
for (let i = 0; i < 1_000_000; i++) {
  createHash('sha256').update('guess' + i).digest();
}
console.log(`1M SHA-256 hashes: ${Math.round(performance.now() - start)} ms`);
f52fbd32b2b3b86ff88ef6c490628285f482af15ddcb29541f94bcf526a3f6c7
f52fbd32b2b3b86ff88ef6c490628285f482af15ddcb29541f94bcf526a3f6c7
1M SHA-256 hashes: 1206 ms
  1. No salt means identical outputs. Every user with the password hunter2 has the same hash, so one lookup in a precomputed table cracks all of them at once.
  2. It's fast. A single CPU core in JavaScript does about a million guesses per second. A GPU does billions. An 8-character password falls in hours.

Password hashing functions fix both problems. They take a random salt, so equal passwords produce different hashes. They also take a cost parameter that makes each guess take tens or hundreds of milliseconds and, for scrypt and Argon2, a lot of memory. Memory is what makes GPU and ASIC attacks expensive.

Which algorithm to choose

Algorithm Where Notes
Argon2id crypto.argon2() (Node.js 24.7+), argon2 npm package First choice. Memory-hard, winner of the Password Hashing Competition
scrypt crypto.scrypt() Memory-hard, built into all Node.js versions. Good choice
bcrypt bcrypt npm package Still fine. Only uses the first 72 bytes of the password
PBKDF2 crypto.pbkdf2() Not memory-hard. Use it when FIPS-140 compliance requires it

OWASP's minimum recommended settings (Password Storage Cheat Sheet):

Hashing with scrypt

crypto.scrypt(password, salt, keylen, options, callback) derives keylen bytes from the password and salt. The options:

The stored string must contain everything needed to verify the password later: the algorithm, the cost parameters, the salt and the derived key. A common format looks like the one used by Argon2 and bcrypt: $algorithm$params$salt$hash.

Here is a complete, reusable module:

// password.mjs
import { scrypt, randomBytes, timingSafeEqual } from 'node:crypto';
import { promisify } from 'node:util';

const scryptAsync = promisify(scrypt);

// current cost settings; raise LOG_N over time as hardware gets faster
const LOG_N = 17; // N = 2^17 = 131072
const R = 8;
const P = 1;
const KEY_LEN = 32;
const SALT_LEN = 16;

function derive(password, salt, logN, r, p, keyLen) {
  const N = 2 ** logN;
  // scrypt uses ~128 * N * r bytes; the default 32 MiB limit is too small
  const maxmem = 256 * N * r;
  return scryptAsync(password.normalize('NFKC'), salt, keyLen, { N, r, p, maxmem });
}

function parse(stored) {
  const [, id, params, saltB64, keyB64] = stored.split('$');
  if (id !== 'scrypt') throw new Error(`unsupported hash type: ${id}`);
  const { ln, r, p } = Object.fromEntries(
    params.split(',').map((kv) => kv.split('=')).map(([k, v]) => [k, Number(v)]),
  );
  return {
    logN: ln, r, p,
    salt: Buffer.from(saltB64, 'base64url'),
    key: Buffer.from(keyB64, 'base64url'),
  };
}

export async function hashPassword(password) {
  const salt = randomBytes(SALT_LEN);
  const key = await derive(password, salt, LOG_N, R, P, KEY_LEN);
  return `$scrypt$ln=${LOG_N},r=${R},p=${P}` +
    `$${salt.toString('base64url')}$${key.toString('base64url')}`;
}

export async function verifyPassword(password, stored) {
  const { logN, r, p, salt, key } = parse(stored);
  const actual = await derive(password, salt, logN, r, p, key.length);
  return timingSafeEqual(actual, key);
}

export function needsRehash(stored) {
  const { logN, r, p, key } = parse(stored);
  return logN < LOG_N || r !== R || p !== P || key.length !== KEY_LEN;
}

Using it:

import { hashPassword, verifyPassword, needsRehash } from './password.mjs';

const hash = await hashPassword('correct horse battery staple');
console.log(hash);
console.log(await verifyPassword('correct horse battery staple', hash));
console.log(await verifyPassword('correct horse battery stapler', hash));
console.log(needsRehash(hash));

// a hash created years ago with N = 2^14
const old = '$scrypt$ln=14,r=8,p=1$c2FsdHNhbHRzYWx0c2FsdA$' +
  'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA';
console.log(needsRehash(old));
$scrypt$ln=17,r=8,p=1$JQ9Y9csY62MCfYg9-bjATQ$UMRiw5L7V-qRgpYMmNPe4INf5ygEVYcSxziTBK7uNZE
true
false
false
true

Run it again and you get a different hash for the same password, because the salt is new every time.

Things worth pointing out:

Don't block the event loop

Password hashing is slow by design: the module above takes about 180 ms per hash. Use the async versions (scrypt, pbkdf2, argon2) in servers. They run on libuv's thread pool and the event loop keeps serving other requests. The *Sync versions block everything:

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

const scryptAsync = promisify(scrypt);
const opts = { N: 2 ** 17, r: 8, p: 1, maxmem: 256 * 2 ** 17 * 8 };

let ticks = 0;
const timer = setInterval(() => ticks++, 10);

let start = performance.now();
for (let i = 0; i < 5; i++) scryptSync('pw', randomBytes(16), 32, opts);
console.log(`sync:  ${Math.round(performance.now() - start)} ms, timer ticks: ${ticks}`);

ticks = 0;
start = performance.now();
await Promise.all(Array.from({ length: 5 }, () => scryptAsync('pw', randomBytes(16), 32, opts)));
console.log(`async: ${Math.round(performance.now() - start)} ms, timer ticks: ${ticks}`);
clearInterval(timer);
sync:  976 ms, timer ticks: 0
async: 419 ms, timer ticks: 27

With scryptSync the 10 ms timer didn't fire even once in almost a second: the process was frozen. The async version ran hashes in parallel and the timer kept firing.

The thread pool has 4 threads by default, shared with fs, dns.lookup() and zlib. If your server hashes many passwords concurrently, increase it with the UV_THREADPOOL_SIZE environment variable (e.g. UV_THREADPOOL_SIZE=8 node server.js), and rate-limit your login endpoint: an attacker can use a slow hash to overload your server.

Login flow

A typical sign-up and login with the password.mjs module:

import { hashPassword, verifyPassword, needsRehash } from './password.mjs';

const users = new Map(); // email -> { passwordHash }

// computed once at startup, used when the user doesn't exist
const DUMMY_HASH = await hashPassword('not-a-real-password');

async function signup(email, password) {
  if (password.length < 8) throw new Error('password must have at least 8 characters');
  if (password.length > 256) throw new Error('password is too long');
  if (users.has(email)) throw new Error('email already registered');
  users.set(email, { passwordHash: await hashPassword(password) });
}

async function login(email, password) {
  const user = users.get(email);
  // always run the slow hash so response time doesn't reveal
  // whether the account exists
  const ok = await verifyPassword(password, user?.passwordHash ?? DUMMY_HASH);
  if (!user || !ok) return false;

  if (needsRehash(user.passwordHash)) {
    // we have the plain-text password right now: upgrade the hash
    user.passwordHash = await hashPassword(password);
  }
  return true;
}

await signup('alice@example.com', 'correct horse battery staple');
console.log(await login('alice@example.com', 'correct horse battery staple'));
console.log(await login('alice@example.com', 'wrong password'));
console.log(await login('bob@example.com', 'whatever'));
true
false
false

Details that matter here:

Argon2id with built-in crypto.argon2()

Node.js 24.7 added crypto.argon2(algorithm, parameters, callback) and crypto.argon2Sync(). It's marked experimental, so check that your Node.js version has it (typeof crypto.argon2 === 'function'). The parameters:

The function returns raw bytes, so encoding to the standard PHC string ($argon2id$v=19$m=...,t=...,p=...$salt$hash) is up to you:

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

const argon2Async = promisify(argon2);

// OWASP minimum for argon2id: 19 MiB memory, 2 passes, 1 lane
const PARAMS = { memory: 19456, passes: 2, parallelism: 1, tagLength: 32 };

export async function hashPassword(password) {
  const nonce = randomBytes(16);
  const tag = await argon2Async('argon2id', { message: password, nonce, ...PARAMS });
  const b64 = (buf) => buf.toString('base64').replace(/=+$/, '');
  return `$argon2id$v=19$m=${PARAMS.memory},t=${PARAMS.passes},p=${PARAMS.parallelism}` +
    `$${b64(nonce)}$${b64(tag)}`;
}

export async function verifyPassword(password, stored) {
  const [, algorithm, , params, nonceB64, tagB64] = stored.split('$');
  const { m, t, p } = Object.fromEntries(
    params.split(',').map((kv) => kv.split('=')).map(([k, v]) => [k, Number(v)]),
  );
  const expected = Buffer.from(tagB64, 'base64');
  const actual = await argon2Async(algorithm, {
    message: password,
    nonce: Buffer.from(nonceB64, 'base64'),
    memory: m, passes: t, parallelism: p,
    tagLength: expected.length,
  });
  return timingSafeEqual(actual, expected);
}

const hash = await hashPassword('correct horse battery staple');
console.log(hash);
console.log(await verifyPassword('correct horse battery staple', hash));
console.log(await verifyPassword('wrong', hash));
$argon2id$v=19$m=19456,t=2,p=1$NmX91XPHhbLgNLbqcnCSFQ$78zGpXCsKIolDmKkrdqoFgAe+vi0PiMZtLci1f71crE
true
false

Because it uses the standard PHC format (unpadded base64), hashes produced this way are interchangeable with the argon2 npm package and with Argon2 libraries in other languages.

Argon2id with the argon2 npm package

On older Node.js versions, or if you prefer a small, battle-tested API, use the argon2 package. It ships prebuilt binaries, so there's usually nothing to compile:

npm install argon2
import argon2 from 'argon2';

// defaults: argon2id, 64 MiB memory, 3 iterations, 4 lanes
const hash = await argon2.hash('correct horse battery staple');
console.log(hash);
console.log(await argon2.verify(hash, 'correct horse battery staple'));
console.log(await argon2.verify(hash, 'wrong'));

// does this hash use different parameters than these?
console.log(argon2.needsRehash(hash, { memoryCost: 65536, timeCost: 3 }));

// explicit parameters
const h = await argon2.hash('pw', {
  type: argon2.argon2id, memoryCost: 19456, timeCost: 2, parallelism: 1,
});
console.log(h);
$argon2id$v=19$m=65536,p=4,t=3$IqIn/XQcI8lkURDJgo4jhQ$sC5vpq+23n7ZqCKIufcofIk4RN3+ztEXx4nIIahWoHQ
true
false
false
$argon2id$v=19$m=19456,p=1,t=2$Smy2qhQS6Fn6gGUd9ImhIg$DgdjeEIukCiUqAr+yGRD6myLZCRE1wKfJRTFTYze9zQ

Note the argument order: argon2.verify(hash, password), hash first. memoryCost is in KiB.

bcrypt

bcrypt has been around since 1999 and is still a reasonable choice. Many existing databases use it, so you'll often need to verify bcrypt hashes even in new code. Use the bcrypt package (native, with prebuilt binaries) or bcryptjs (pure JavaScript, slower, same API):

npm install bcrypt
import bcrypt from 'bcrypt';

const hash = await bcrypt.hash('correct horse battery staple', 12); // cost factor 12
console.log(hash);
console.log(await bcrypt.compare('correct horse battery staple', hash));
console.log(await bcrypt.compare('wrong', hash));
console.log(bcrypt.getRounds(hash));
$2b$12$4PwcMquJvJCoCRiGv0/Y/OfuXXKX8x7jGxC/8fgfEgPGrjvrqCm3q
true
false
12

The cost factor is logarithmic: each +1 doubles the time. bcrypt generates and embeds the salt for you, and $2b$12$ records the version and cost.

The 72-byte limit: bcrypt ignores everything after the first 72 bytes of the password. Two long passwords with the same 72-byte prefix are considered equal:

const prefix = 'x'.repeat(72);
const h = await bcrypt.hash(prefix + 'AAAA', 10);
console.log(await bcrypt.compare(prefix + 'BBBB', h)); // true!

Non-ASCII characters take 2-4 bytes in UTF-8, so the limit can be reached with fewer than 72 characters. Either cap the password length at 72 bytes (Buffer.byteLength(password) <= 72) or pre-hash as shown in the next section.

Pepper: a server-side secret

A salt is stored with the hash, so an attacker who dumps the database has it. A pepper is an additional secret key that is not stored in the database: it lives in an environment variable or a secrets manager. If only the database leaks, the hashes can't be attacked offline at all.

Apply the pepper with HMAC before the password hash. With bcrypt, this also fixes the 72-byte limit, since the base64 HMAC is always 44 characters:

import { createHmac } from 'node:crypto';
import bcrypt from 'bcrypt';

// 32+ random bytes, loaded from an env var or secrets manager - not stored in the DB
const PEPPER = Buffer.from(process.env.PASSWORD_PEPPER ?? 'dev-only-pepper', 'utf8');

function prehash(password) {
  // 44 chars of base64: under bcrypt's 72-byte limit, no NUL bytes
  return createHmac('sha256', PEPPER).update(password.normalize('NFKC')).digest('base64');
}

const long = 'x'.repeat(72);
const hash = await bcrypt.hash(prehash(long + 'AAAA'), 12);
console.log(await bcrypt.compare(prehash(long + 'AAAA'), hash));
console.log(await bcrypt.compare(prehash(long + 'BBBB'), hash));
true
false

Use base64 or hex output, not the raw digest: raw bytes can contain a 0x00 byte, and some bcrypt implementations stop at the first NUL.

The downside: if you lose the pepper, every user has to reset their password. And rotating it requires the same rehash-on-login approach as changing cost parameters.

Normalize Unicode

The same visible password can be typed as different code point sequences. é can be one code point or e followed by a combining accent, depending on the OS and keyboard:

const composed = 'café';     // é as one code point
const decomposed = 'cafe\u0301'; // e + combining acute accent
console.log(composed === decomposed);
console.log(composed.length, decomposed.length);
console.log(composed.normalize('NFKC') === decomposed.normalize('NFKC'));
false
4 5
true

Without normalization a user who signed up on a Mac might not be able to log in from Windows. Call password.normalize('NFKC') (as recommended by NIST SP 800-63B) before hashing, both at sign-up and at login. Whatever you choose, do it consistently from day one: changing it later breaks existing hashes.

PBKDF2

PBKDF2 isn't memory-hard, so GPUs crack it more efficiently than scrypt or Argon2. Use it when a standard requires it (FIPS-140), and use a high iteration count:

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

const pbkdf2Async = promisify(pbkdf2);
const ITERATIONS = 600_000; // OWASP recommendation for PBKDF2-HMAC-SHA256

async function hashPassword(password) {
  const salt = randomBytes(16);
  const key = await pbkdf2Async(password, salt, ITERATIONS, 32, 'sha256');
  return `pbkdf2_sha256$${ITERATIONS}$${salt.toString('base64')}$${key.toString('base64')}`;
}

async function verifyPassword(password, stored) {
  const [, iterations, saltB64, keyB64] = stored.split('$');
  const expected = Buffer.from(keyB64, 'base64');
  const actual = await pbkdf2Async(password, Buffer.from(saltB64, 'base64'),
    Number(iterations), expected.length, 'sha256');
  return timingSafeEqual(actual, expected);
}

const hash = await hashPassword('s3cret');
console.log(hash);
console.log(await verifyPassword('s3cret', hash));
pbkdf2_sha256$600000$cvd1b3ee+1kRR42gkpIARQ==$aQnOK+6CyrTWy7k0saGZBvl1G5yJcSZ4qPpe0p6fcEw=
true

Don't ask for more output bytes than the hash produces (32 for SHA-256): PBKDF2 then runs all iterations again for each extra block, doubling your cost but not the attacker's.

Choosing the cost

The right cost is the highest your servers can afford. Aim for roughly 100-500 ms per hash on your production hardware, measured with a loop like this:

import { hashPassword } from './password.mjs';

const start = performance.now();
for (let i = 0; i < 10; i++) await hashPassword('benchmark');
console.log(`${((performance.now() - start) / 10).toFixed(0)} ms per hash`);

Remember the memory: scrypt with N=2^17 and Argon2id with 64 MiB use that much RAM per concurrent hash. 20 simultaneous logins at 128 MiB each is 2.5 GiB. On small containers, prefer a lower memory setting with more iterations.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents