← Back to Backend, page 1

backend-0009 · Easy fresher

How should passwords be stored: why do you need a salt and a slow hash, and how do you verify and upgrade stored hashes?

Never store passwords in plain text or with a fast hash such as SHA-256. Use a memory-hard, slow password hash (argon2id, scrypt or bcrypt) with a unique random salt per user, so identical passwords give different hashes and attackers cannot use precomputed tables. Store the algorithm, its parameters and the salt with the hash, compare with a constant-time check, and re-hash at login when the parameters are outdated.

Full answer

Why a plain hash is not enough

  • Fast hashes let an attacker with a stolen database test billions of guesses per second on a GPU.
  • Without a salt, equal passwords have equal hashes, and rainbow tables work.

What to do

  1. Use argon2id (preferred), scrypt or bcrypt. They are slow on purpose and (for argon2 and scrypt) need a lot of memory, which limits parallel guessing.
  2. Create a random salt (16 bytes or more) for every password. It is not secret. Store it next to the hash.
  3. Store everything needed to verify in one string, for example algorithm$params$salt$hash. This lets you change the cost later.
  4. Verify by recomputing with the stored salt and parameters, and compare with crypto.timingSafeEqual to avoid timing leaks.
  5. After a successful login, if the stored parameters are weaker than the current policy, hash again and update the record (rehash on login).
  6. Optionally add a pepper (a secret kept outside the database, for example in a key vault). Limit login attempts and use breached password checks. Enforce a sensible length limit, because very long inputs make hashing a denial of service vector.

Node.js ships with crypto.scrypt. Argon2 needs a library.

javascript
const crypto = require('node:crypto');
const { promisify } = require('node:util');
const scrypt = promisify(crypto.scrypt);

const PARAMS = { N: 16384, r: 8, p: 1, keylen: 32 };

async function hashPassword(password, params = PARAMS) {
  const salt = crypto.randomBytes(16);
  const key = await scrypt(password, salt, params.keylen, { N: params.N, r: params.r, p: params.p });
  return ['scrypt', params.N, params.r, params.p, salt.toString('base64'), key.toString('base64')].join('$');
}

async function verifyPassword(password, stored) {
  const [alg, N, r, p, salt, hash] = stored.split('$');
  if (alg !== 'scrypt') return { ok: false };
  const expected = Buffer.from(hash, 'base64');
  const key = await scrypt(password, Buffer.from(salt, 'base64'), expected.length, { N: +N, r: +r, p: +p });
  const ok = crypto.timingSafeEqual(key, expected);
  return { ok, needsRehash: ok && (+N < PARAMS.N || +r < PARAMS.r) };
}

(async () => {
  const a = await hashPassword('correct horse battery');
  const b = await hashPassword('correct horse battery');
  console.log('same password, different hashes:', a !== b);
  console.log('stored format                  :', a.split('$').slice(0, 4).join('$') + '$<salt>$<hash>');
  console.log('right password                 :', JSON.stringify(await verifyPassword('correct horse battery', a)));
  console.log('wrong password                 :', JSON.stringify(await verifyPassword('wrong', a)));

  const old = await hashPassword('secret', { N: 4096, r: 8, p: 1, keylen: 32 });
  console.log('old hash, right password       :', JSON.stringify(await verifyPassword('secret', old)), '(rehash with current cost and save it)');

  const sha = crypto.createHash('sha256').update('secret').digest('hex');
  console.log('plain SHA-256 is the same for every user of "secret":', sha === crypto.createHash('sha256').update('secret').digest('hex'));
})();

Uses the built-in crypto.scrypt. The cost of 16384 is a teaching value. Pick the cost from your own measurements and current guidance, and prefer argon2id when a library is allowed. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): same password, different hashes: true stored format : scrypt$16384$8$1$<salt>$<hash> right password : {"ok":true,"needsRehash":false} wrong password : {"ok":false,"needsRehash":false} old hash, right password : {"ok":true,"needsRehash":true} (rehash with current cost and save it) plain SHA-256 is the same for every user of "secret": true

Key points

  • Use a slow, memory-hard password hash with a unique salt.
  • Store algorithm, parameters and salt with the hash.
  • Compare with a constant-time function.
  • Rehash at login when parameters are outdated.
  • Rate limit logins and set a maximum password length.

Common mistakes

  • Using MD5, SHA-1 or plain SHA-256 for passwords.
  • One global salt for all users.
  • Comparing hashes with ===.
  • Never raising the cost as hardware improves.
  • Allowing megabyte-long passwords.

Follow-ups

  • What does argon2id add over scrypt and bcrypt?
  • What is a pepper and where do you keep it?
  • How do you migrate users from an old hash to a new one?

Tips

  • Say 'slow, salted, constant-time compare'.
  • Mention rehash on login.
  • Name argon2id.