More Node.js answers

by Danny
Published 2 min read

Hash passwords with a slow, salted algorithm such as scrypt or Argon2id, never SHA-256. Learn how to do it with node:crypto and compare hashes safely with timingSafeEqual.

The short answer

#

Use a password hashing function that is deliberately slow and uses a random salt. Node.js has crypto.scrypt built in, which needs no dependencies. Store the salt and parameters with the hash, and compare with crypto.timingSafeEqual when the user logs in.


_12
import { scrypt, randomBytes, timingSafeEqual } from 'node:crypto';
_12
import { promisify } from 'node:util';
_12
_12
const scryptAsync = promisify(scrypt);
_12
const KEY_LENGTH = 64;
_12
const PARAMS = { N: 2 ** 17, r: 8, p: 1, maxmem: 256 * 1024 * 1024 };
_12
_12
export async function hashPassword(password) {
_12
const salt = randomBytes(16);
_12
const key = await scryptAsync(password.normalize('NFKC'), salt, KEY_LENGTH, PARAMS);
_12
return ['scrypt', PARAMS.N, PARAMS.r, PARAMS.p, salt.toString('base64'), key.toString('base64')].join('$');
_12
}

Why it happens

#

Password hashes get leaked: through a database backup, a SQL injection bug or a stolen laptop. Once an attacker has the hashes, they guess passwords offline as fast as their hardware allows.

General hash functions such as SHA-256 or MD5 are designed to be fast, so a single graphics card can try billions of guesses a second. Password hashing functions such as scrypt, Argon2id and bcrypt are designed to be slow and, in the case of scrypt and Argon2, to need a lot of memory, which makes each guess expensive. A unique random salt per password means two users with the same password get different hashes, and precomputed tables are useless.

How to fix it

#

Hash with scrypt and store the parameters

The example above uses the parameters OWASP recommends for scrypt: N of 2 to the power 17, r of 8 and p of 1. That needs about 128 MiB per hash, which is more than the 32 MiB default limit in Node.js, so maxmem has to be raised.

The stored string keeps the algorithm, parameters and salt next to the hash. Later you can raise the cost for new passwords and still verify old ones.

Verify with timingSafeEqual

Read the parameters back from the stored string, hash the attempt the same way, and compare in constant time. A normal === comparison can leak how many leading bytes matched through tiny timing differences.


_14
export async function verifyPassword(password, stored) {
_14
const [algorithm, N, r, p, saltB64, keyB64] = stored.split('$');
_14
if (algorithm !== 'scrypt') return false;
_14
_14
const expected = Buffer.from(keyB64, 'base64');
_14
const actual = await scryptAsync(
_14
password.normalize('NFKC'),
_14
Buffer.from(saltB64, 'base64'),
_14
expected.length,
_14
{ N: Number(N), r: Number(r), p: Number(p), maxmem: 256 * 1024 * 1024 },
_14
);
_14
_14
return timingSafeEqual(actual, expected);
_14
}

timingSafeEqual throws if the buffers have different lengths. Deriving actual with expected.length keeps them equal.

Use Argon2id or bcrypt through a library

OWASP currently lists Argon2id as its first choice. The argon2 package on npm is a well-established option and produces self-describing hash strings, so you do not have to build the format yourself.


_10
import argon2 from 'argon2';
_10
_10
const hash = await argon2.hash(password, { type: argon2.argon2id });
_10
const ok = await argon2.verify(hash, password);

Node.js 24.7.0 also added a built-in crypto.argon2(). It is newer than scrypt, so check its stability status in the crypto docs for your Node.js version before relying on it.

bcrypt, through the bcrypt or bcryptjs packages, is still acceptable for existing systems. It only uses the first 72 bytes of a password, so very long passphrases are silently truncated.

Common pitfalls

#
  • Using SHA-256, even with a salt. It is far too fast for passwords.
  • Using the synchronous scryptSync in a request handler. It blocks the event loop; the async version runs on the thread pool.
  • Not thinking about concurrency. Each scrypt hash with these settings uses about 128 MiB, so many logins at once can use a lot of memory. Rate-limit your login endpoint.
  • Reusing one salt for every user. Generate a new one with randomBytes for every hash.
  • Writing your own scheme, such as hashing several times in a loop. Use the algorithms as designed.
#

Was this resource helpful?