Courses / Node.js: From First Script to Production / Chapter 18
Module 8 · Production services · Chapter 18 of 27
Authentication, Authorisation and Securing a Node App
Builds on npm and Package Management: Dependencies, Versions and Lockfiles, Advanced Topics: Child Processes, Worker Threads, Cluster and Debugging, The libuv Thread Pool and Blocking Work, Working with Databases: A REST API on PostgreSQL and Production APIs: Validation, Error Shapes, Idempotency and Fastify. Next up: Caching and Background Jobs in Node Services.
Part 1 · Storing passwords: salts, scrypt and argon2id
Why a password is never stored as typed
Databases leak, through bugs, stolen backups and careless access. Whatever you store is what an attacker gets, so store something useless without a long computation.
Plain text fails at once: one leak hands over every account, and people reuse passwords across sites. A fast hash such as SHA-256 is better but still weak, because the attacker can try guesses at the same speed that you can compute hashes. The script below shows that speed on this machine: it hashes 200,000 short strings with SHA-256, then runs 20 scrypt hashes at a modest cost setting.
import { createHash, scryptSync } from 'node:crypto'; const salt = 'fixedsaltvalue16'; let t0 = performance.now(); for (let i = 0; i < 200_000; i++) { createHash('sha256').update('pass' + i).digest(); } const fast = performance.now() - t0; console.log('200000 SHA-256 hashes:', Math.round(fast), 'ms'); t0 = performance.now(); for (let i = 0; i < 20; i++) { scryptSync('pass' + i, salt, 64, { N: 2 ** 14, r: 8, p: 1 }); } const slow = performance.now() - t0; console.log('20 scrypt hashes (N=2^14):', Math.round(slow), 'ms'); console.log('per guess, scrypt costs about', Math.round(slow / 20 / (fast / 200_000)), 'times more');
l1-fast.mjs