Skip to content
Tutorials Center
My learning

Topics

Lesson 76 of 133 ยท Security and Cryptography

Passwords, scrypt and Tokens

Store passwords safely in Node.js with scrypt, salts and timingSafeEqual, then build and verify a signed HS256 token by hand, with expiry, refresh tokens and session safety rules.

Every application with accounts faces the same question: what do you store so users can log in, without making a database leak a disaster? The answer is never the password itself and never a plain fast hash of it. You store the result of a deliberately slow, salted password hash, and you compare candidates against it in constant time. After login, the user needs to stay logged in without sending the password again, which is the job of a session or a signed token.

This lesson covers both halves with the built-in node:crypto module: hashing and verifying passwords with scrypt, adding a pepper, upgrading old hashes, then building a signed token (a tiny JWT-style format) by hand so you understand exactly what libraries do. It builds on Hashing and HMAC and Randomness and Identifiers, and the key-derivation ideas from Encryption: AES, RSA and Keys.

Why not just SHA-256?

A hash like SHA-256 is designed to be fast: a modern graphics card tests billions of guesses per second. If an attacker steals a table of sha256(password) values, common passwords fall in minutes, and identical passwords produce identical hashes, so cracking one cracks every user who shares it. Password hashing needs three properties that plain hashes lack:

  1. Salt: random bytes, unique per user, mixed in before hashing. Two users with the same password get different hashes, and precomputed "rainbow tables" become useless. A salt is not secret; you store it with the hash.
  2. Slowness: the function is tuned to take tens of milliseconds, which is nothing for one login and ruinous for a billion guesses.
  3. Memory hardness: algorithms such as scrypt need a lot of RAM per guess, which makes cheap parallel hardware (GPUs, ASICs) far less effective.

Node includes scrypt (memory-hard) and pbkdf2 (slow but not memory-hard). Argon2id is the other modern choice, but it is not in Node's standard library, so scrypt is the best built-in option.

Hashing with scrypt

crypto.scrypt (callback, also usable with promisify) and scryptSync take a password, a salt and an output length. The defaults, N = 16384 (CPU/memory cost), r = 8, p = 1, are the minimum reasonable settings today. The demo below fixes the salt so you get the same output on every run; real code uses randomBytes(16).

Node.js The same password with different salts

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The first comparison is true because scrypt is deterministic: that is what lets you verify a login later. The second is false because the salt changed the result completely.

A storage format you can verify later

When you save the hash you must also save everything needed to recompute it: the algorithm, its cost parameters, the salt and the hash. A single string keeps these together and lets you raise the cost in the future without breaking old accounts. The format below is similar to the ones used by other password libraries.

Node.js hashPassword and verifyPassword

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Study the pieces:

  • promisify(scrypt) turns the callback API into a promise so the work runs on libuv's thread pool and does not block the event loop. Prefer the async version in a server: scryptSync freezes every other request while it computes (see The Event Loop and The util Module).
  • timingSafeEqual compares two buffers in time that does not depend on how many bytes match. Using === on strings can leak, through response timing, how much of a guess was right. It throws if the lengths differ, so make sure both buffers have the same size first.
  • The cost parameters live in the stored string, so you can raise COST later and still verify old hashes.

Tune the cost so one hash takes about 50 to 250 ms on your production hardware, and measure it there. Too cheap helps attackers; too expensive lets a flood of login attempts exhaust your CPU. Rate-limit login endpoints either way (see Web Application Security).

Upgrading hashes over time

Hardware gets faster, so cost settings age. Because the parameters are stored with each hash, you can detect an old hash after a successful login (the only moment you hold the plaintext) and silently re-hash with stronger settings.

Node.js Re-hash on login when the cost is outdated

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice maxmem: scrypt uses about 128 * N * r bytes, and Node refuses to run if that exceeds its default limit (32 MB). When you raise N you may need to raise maxmem too.

Pepper: a secret outside the database

A pepper is a secret value, the same for all users, that is not stored in the database. Applying it with HMAC before hashing means a stolen database alone is not enough to crack passwords, because the attacker also needs the pepper from your configuration or secret manager.

NODE
// Read-only sketch: the pepper comes from configuration, never from source code.
import { createHmac } from 'node:crypto';

function applyPepper(password) {
  return createHmac('sha256', process.env.PASSWORD_PEPPER).update(password).digest();
}
// then: scrypt(applyPepper(password), salt, ...)

A pepper is an extra layer, not a replacement for salting and slow hashing. Treat it like any other secret (Configuration, Secrets and Environment), and plan for rotation by storing a pepper version number alongside each hash.

Signed tokens by hand

After a successful login the server needs to remember who you are. There are two classic designs:

  • Server-side sessions: the server stores the session data and gives the browser a random, meaningless session ID in a cookie. Revoking a session is trivial (delete the row).
  • Signed tokens: the server gives the client a self-contained token holding claims such as sub (user id) and exp (expiry), plus a signature. The server needs no lookup to trust it, but cannot easily revoke it before it expires.

A JWT (JSON Web Token) is the best-known token format: three base64url parts, header.payload.signature, joined by dots. The signature is an HMAC (HS256) or a public-key signature (RS256, EdDSA) over the first two parts. Building HS256 yourself takes about twenty lines, and it makes clear what a library actually does. The code below fixes the clock with a now parameter so every run prints the same result.

Node.js Sign and verify an HS256 token

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Read the code once more with these rules in mind:

  • The payload is encoded, not encrypted. Anyone can decode it, as the payload line of the output shows. Never put secrets in a JWT.
  • Verification recomputes the HMAC over exactly the bytes received and compares in constant time.
  • The alg check matters. Famous JWT bugs came from libraries that trusted the algorithm named in the token itself, including the value none. Your verifier must decide which algorithm is acceptable, not the token.
  • Expiry (exp) limits the damage of a stolen token. Keep access tokens short (minutes), because you generally cannot revoke them.

Tampering fails verification

An attacker can edit the payload to claim a higher role, but cannot produce a matching signature without the secret.

Node.js Forging a role (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The program prints original: student, then throws Error: invalid signature with a stack trace pointing at the throw line in main.mjs. (This quick version compares strings with !==; the previous example shows the constant-time version you should actually use.)

Refresh tokens

Short-lived access tokens are safer but would force users to log in every fifteen minutes. The standard solution is a pair:

  • an access token (minutes) sent with each API call, and
  • a refresh token (days or weeks) used only to get a new access token.

Make the refresh token an opaque random string (for example randomBytes(32).toString('base64url')), not a JWT. Store only its hash in your database, linked to the user and device. That way you can revoke it, list a user's active devices, and a database leak does not reveal usable tokens. Good implementations rotate refresh tokens: each use returns a new one and invalidates the old, so a stolen token that is used twice triggers an alarm.

Sessions, cookies and fixation

If you use server-side sessions, three rules prevent the classic attacks:

  • Regenerate the session ID at login. In a session fixation attack the attacker plants a known session ID in the victim's browser before login; if the server keeps that ID after authentication, the attacker is now logged in too.
  • Set cookie flags: HttpOnly (JavaScript cannot read it), Secure (HTTPS only) and SameSite=Lax or Strict (limits cross-site sending). Cookie handling is covered in Headers, Cookies and Caching.
  • Expire and revoke. Give sessions an idle timeout and an absolute lifetime, and delete them on logout and on password change.

What never to do

  • Never store plaintext passwords, reversibly encrypted passwords, or unsalted/fast hashes (MD5, SHA-1, SHA-256).
  • Never write your own hashing loop or invent a token format when a vetted one exists.
  • Never log passwords, tokens or full Authorization headers, even in debug logs.
  • Never compare secrets with ===; use timingSafeEqual (or compare hashes of both sides).
  • Never put sensitive data in a JWT payload, and never accept the algorithm the token asks for.
  • Never tell the user which half of a login was wrong. "Invalid email or password" avoids leaking which emails have accounts, and perform the hash work even for unknown emails so timing does not reveal them either.
  • Never skip rate limiting and lockout/slow-down logic on login and password reset endpoints.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the main purpose of a salt in password hashing?

    A unique random salt per user means equal passwords hash differently and rainbow tables cannot be reused. The salt is not secret and is stored with the hash.
  2. 2. Why do password hashes use deliberately slow, memory-hungry algorithms such as scrypt?

    A cost of tens of milliseconds is negligible for one login but multiplies across billions of guesses, and memory hardness limits GPU and ASIC speedups.
  3. 3. Which call should you use to compare a computed hash with a stored one?

    timingSafeEqual takes the same time whether the buffers match early or late, so response timing cannot leak information. Both buffers must have equal length.
  4. 4. What is true about the payload of a standard signed JWT?

    Signing provides integrity, not secrecy. Keep sensitive data out of tokens or use an encrypted token format.
  5. 5. How does regenerating the session ID at login protect users?

    If the ID stayed the same after authentication, an attacker who knew it in advance would share the victim's logged-in session.

Summary

  • Store passwords only as salted, slow hashes. In Node, use crypto.scrypt (async) with a random 16-byte salt, and keep the algorithm, cost and salt in the stored string.
  • Compare with timingSafeEqual, return the same message for every failed login, and re-hash with stronger parameters after a successful login when the stored cost is outdated.
  • A pepper kept outside the database adds a layer; it never replaces salting and slow hashing.
  • A JWT-style token is header.payload.signature: the payload is readable by anyone, the signature (HMAC or public-key) guarantees integrity, and exp limits the lifetime. Your verifier chooses the accepted algorithm.
  • Use short access tokens plus opaque, hashed, rotating refresh tokens so sessions can be revoked.
  • With cookie sessions, regenerate the ID at login, set HttpOnly, Secure and SameSite, and expire sessions.

Next: Web Application Security