Node.js 51 🟢 Password Hashing with bcrypt, Argon2, and Native Web Crypto
Password hashing is the last line of defense when a database is compromised. The choice of algorithm and its configuration determines how long an attacker must spend to recover each password. Node.js offers three viable paths: the bcrypt npm package, the argon2 npm package, and the built-in crypto.scrypt function. Each has a different operational profile, and the right choice depends on your environment and threat model.
The threat model is different from data integrity. You never need to recover a password from its hash, so the function is one-way. It must include a salt to defeat rainbow tables, and it must be tunable so you can increase the cost as hardware improves. The three algorithms discussed here are all adaptive: their cost parameters can be raised without changing the stored format.
This chapter covers the three algorithms, their parameter choices, the pitfalls specific to each, and the patterns for integrating them into a Node.js application. It closes with the operational concerns: rehashing on login, constant-time comparison, and the timing side channels that leak information when comparisons are done carelessly.
Key point: Never use SHA-256 or MD5 for passwords. These are fast hashes designed for data integrity, not for protecting low-entropy secrets. A purpose-built password hashing function must be deliberately slow and salted.
Why password hashing requires specialized algorithms
The speed problem. General-purpose hashes like SHA-256 compute in microseconds. That speed benefits attackers running offline cracking rigs, who can test billions of guesses per second on commodity GPUs. A password hashing function must be slow by design, so each guess costs meaningful time and resources.
The low-entropy problem. Passwords are not cryptographic keys. They are short, human-chosen strings with perhaps 30 to 40 bits of entropy in the best case. An attacker with a fast hash can exhaust the space of plausible passwords. A slow hash raises the cost of each guess, which multiplies across the space and makes the attack impractical.
The salt problem. Without a salt, identical passwords produce identical hashes. An attacker with a precomputed rainbow table can reverse every hash in a leaked database instantly. A salt is a random value unique to each password, stored alongside the hash, which makes precomputation useless.
The hardware problem. CPUs get faster every year. A hash that took 100 milliseconds in 2015 takes 10 milliseconds today. An adaptive function has tunable cost parameters, so the work can be increased as hardware improves without changing the stored format.
The memory problem. Some algorithms are memory-hard: they require large amounts of RAM during computation. GPUs and ASICs excel at parallel computation but have limited memory bandwidth, so memory-hard functions resist the hardware that makes fast hashes attackable.
The comparison problem. Even with a strong hash, comparing the stored hash to a candidate with === leaks information through response timing. The comparison must be constant-time, so an attacker cannot learn how many bytes matched.
a. bcrypt
bcrypt is the most widely used password hashing algorithm in Node.js. It is CPU-bound, salted automatically, and has a single cost factor that doubles the work with each increment.
Basic usage
The bcrypt package wraps a native C++ implementation. Hash on signup, compare on login.
const bcrypt = require("bcrypt");
const SALT_ROUNDS = 12;
const hash = await bcrypt.hash(password, SALT_ROUNDS);
const ok = await bcrypt.compare(submitted, hash);
The hash string embeds the version, cost, salt, and digest. You store only that string. The compare function re-derives the hash from the submitted password and the stored salt, then compares in constant time.
The 72-byte limit
bcrypt only considers the first 72 bytes of input. Anything beyond is silently ignored, so two passwords sharing the first 72 bytes produce the same hash. This is 72 bytes, not characters; multibyte characters consume more.
The safe fix is to pre-hash with SHA-256 and base64-encode the digest before passing it to bcrypt. Django and other frameworks use this technique to support arbitrarily long passwords.
const crypto = require("crypto");
const prehash = (p) => crypto.createHash("sha256").update(p).digest("base64");
await bcrypt.hash(prehash(password), 12);
Native versus pure JavaScript
The bcrypt package needs a C++ toolchain during install. In Docker or serverless environments where builds fail, bcryptjs is a pure-JavaScript alternative with an identical API and compatible hashes, at the cost of slower execution.
b. Argon2id
Argon2 won the 2015 Password Hashing Competition and is standardized in RFC 9106. It is memory-hard, meaning attackers must pay for RAM as well as CPU. The id variant is the hybrid recommended for password storage.
Basic usage
The argon2 package ships its own TypeScript declarations and uses Argon2id by default.
import * as argon2 from "argon2";
const hash = await argon2.hash(password, {
type: argon2.argon2id,
memoryCost: 19456, // 19 MiB
timeCost: 2,
parallelism: 1,
});
const ok = await argon2.verify(hash, password);
The PHC string embeds algorithm, version, memory, iterations, parallelism, salt, and hash in one column. Verification reads the parameters from the stored string, so no separate configuration is needed.
Parameter tuning
OWASP recommends m=19456 (19 MiB), t=2, p=1 for login endpoints. Higher-security contexts can use m=65536 (64 MiB), t=3, p=4. Argon2id sets memory and iterations independently, so you can increase memory without making logins proportionally slower, which is not possible with scrypt.
Rehashing on login
When you raise parameters, old hashes need upgrading. argon2.needsRehash() detects outdated parameters after a successful verification, and you re-hash the password at that moment.
if (ok && argon2.needsRehash(stored, { memoryCost: 65536, timeCost: 3 })) {
const newHash = await argon2.hash(password, { memoryCost: 65536, timeCost: 3 });
// store newHash
}
c. Native Web Crypto: scrypt
Node.js has scrypt built in via crypto.scrypt. No npm package is needed. It is memory-hard and a sound second choice when Argon2id is unavailable.
Basic usage
scrypt requires raising maxmem above Node’s 32 MiB default when using OWASP parameters.
import { scrypt, randomBytes, timingSafeEqual } from "node:crypto";
import { promisify } from "node:util";
const scryptAsync = promisify(scrypt);
const N = 131072, r = 8, p = 1, KEYLEN = 64;
const salt = randomBytes(16);
const key = await scryptAsync(password, salt, KEYLEN, {
N, r, p, maxmem: 256 * N * r,
});
Store the salt and parameters alongside the derived key. scrypt has no standard hash encoding format, so you must serialize the components yourself.
Constant-time comparison
Never compare hashes with ===. Use crypto.timingSafeEqual after re-deriving the key from the stored salt.
const expected = Buffer.from(storedKey, "base64");
const actual = await scryptAsync(password, salt, expected.length, opts);
return timingSafeEqual(actual, expected);
Without constant-time comparison, response timing leaks how many bytes of the guess matched, enabling byte-by-byte recovery.
Complete Example Session
// ============================================
// PART 1: bcrypt WITH PRE-HASHING
// ============================================
const bcrypt = require("bcrypt");
const crypto = require("crypto");
const prehash = (p) => crypto.createHash("sha256").update(p).digest("base64");
async function bcryptHash(password) {
return bcrypt.hash(prehash(password), 12);
}
async function bcryptVerify(password, hash) {
return bcrypt.compare(prehash(password), hash);
}
// ============================================
// PART 2: ARGON2ID WITH OWASP PARAMETERS
// ============================================
const argon2 = require("argon2");
const ARGON_OPTS = {
type: argon2.argon2id,
memoryCost: 19456,
timeCost: 2,
parallelism: 1,
};
async function argonHash(password) {
return argon2.hash(password, ARGON_OPTS);
}
async function argonVerify(password, hash) {
try {
return await argon2.verify(hash, password);
} catch {
return false;
}
}
// ============================================
// PART 3: SCRYPT WITH TIMING-SAFE COMPARE
// ============================================
const { scrypt, randomBytes, timingSafeEqual } = require("node:crypto");
const { promisify } = require("node:util");
const scryptAsync = promisify(scrypt);
async function scryptHash(password) {
const salt = randomBytes(16);
const key = await scryptAsync(password, salt, 64, {
N: 131072, r: 8, p: 1, maxmem: 256 * 131072 * 8,
});
return `scrypt$${salt.toString("base64")}$${key.toString("base64")}`;
}
async function scryptVerify(password, stored) {
const [, saltB64, keyB64] = stored.split("$");
const salt = Buffer.from(saltB64, "base64");
const expected = Buffer.from(keyB64, "base64");
const actual = await scryptAsync(password, salt, expected.length, {
N: 131072, r: 8, p: 1, maxmem: 256 * 131072 * 8,
});
return timingSafeEqual(actual, expected);
}
// ============================================
// PART 4: EXPRESS LOGIN ROUTE
// ============================================
app.post("/login", async (req, res) => {
try {
const user = await findUserByEmail(req.body.email);
if (!user) {
await bcrypt.hash("dummy", 12);
return res.status(401).json({ error: "invalid credentials" });
}
const ok = await bcryptVerify(req.body.password, user.passwordHash);
if (!ok) return res.status(401).json({ error: "invalid credentials" });
res.json({ ok: true });
} catch (err) {
res.status(500).json({ error: "login failed" });
}
});
// ============================================
// PART 5: REHASHING ON LOGIN
// ============================================
async function verifyAndRehash(password, stored) {
const ok = await argonVerify(password, stored);
if (ok && argon2.needsRehash(stored, { memoryCost: 65536, timeCost: 3 })) {
return { ok: true, newHash: await argonHash(password) };
}
return { ok, newHash: null };
}
The five parts showed bcrypt with pre-hashing, Argon2id with OWASP parameters, scrypt with timing-safe comparison, an Express login route with dummy hashing to prevent user enumeration, and the rehashing pattern for parameter upgrades.
Quick Reference
| Algorithm | Node Availability | Memory-Hard | Input Limit | Best For |
|---|---|---|---|---|
| bcrypt | npm bcrypt | No (~4 KB) | 72 bytes | Legacy systems, ubiquitous |
| Argon2id | npm argon2 | Yes (tunable) | None | New projects, first choice |
| scrypt | Built-in crypto | Yes (tunable) | None | No-dependency environments |
OWASP minimum parameters: Argon2id: m=19 MiB, t=2, p=1. scrypt: N=2^17, r=8, p=1. bcrypt: cost 10+.
Best Practices
✅ Do This:
// Use Argon2id for new projects
await argon2.hash(password, { type: argon2.argon2id, memoryCost: 19456 });
// Pre-hash before bcrypt
await bcrypt.hash(sha256(password), 12);
// Compare in constant time
timingSafeEqual(Buffer.from(a), Buffer.from(b));
// Rehash on login when parameters change
if (argon2.needsRehash(hash, newOpts)) { /* rehash */ }
❌ Don’t Do This:
// Never use fast hashes
crypto.createHash("sha256").update(password).digest("hex");
// Never compare with ===
if (hash === storedHash) { } // timing leak
// Never use sync hashing in servers
bcrypt.hashSync(password, 12); // blocks event loop
// Never truncate silently
bcrypt.hash(password, 12); // if password > 72 bytes
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Long passwords collide | bcrypt truncates at 72 bytes | Pre-hash with SHA-256 |
| Timing attacks | === comparison leaks | Use timingSafeEqual |
| Event loop blocked | Sync hashing in request handler | Use async hash/compare |
| scrypt maxmem error | Node default is 32 MiB | Set maxmem: 256 * N * r |
| Native build fails | No C++ toolchain | Use bcryptjs or scrypt |
| Parameters outdated | Hardware improved | Rehash on login with needsRehash |
Real-World Examples
1. bcrypt prehash
bcrypt.hash(sha256(p), 12)
2. Argon2id OWASP
argon2.hash(p, { type: argon2.argon2id, memoryCost: 19456 })
3. scrypt with maxmem
scrypt(p, salt, 64, { N: 131072, maxmem: 256 * 131072 * 8 })
4. Constant-time compare
timingSafeEqual(Buffer.from(a), Buffer.from(b))
5. Dummy hash for user enum
await bcrypt.hash("dummy", 12)
6. Rehash on login
if (argon2.needsRehash(stored, newOpts)) rehash()
7. TypeScript argon2
const hash: string = await argon2.hash(p)
8. scrypt serialization
`scrypt$${salt}$${key}`
9. bcryptjs fallback
import bcrypt from "bcryptjs"
10. Rate limiting
app.use("/login", rateLimit({ windowMs: 60000, max: 5 }))
Visual
The Password Hashing Pipeline
┌────────────────────────────────────────────────────────────┐
│ PASSWORD → SALT → SLOW HASH → STORED HASH │
│ │
│ ┌──────────┐ ┌──────────┐ ┌──────────────────────┐ │
│ │ Password │──▶│ Random │──▶│ bcrypt / Argon2id / │ │
│ │ (input) │ │ Salt │ │ scrypt (slow, memory-│ │
│ └──────────┘ │ (16 B) │ │ hard) │ │
│ └──────────┘ └──────────┬───────────┘ │
│ │ │
│ v │
│ ┌──────────────────────────────────────────────────┐ │
│ │ STORED HASH (salt + digest + parameters) │ │
│ │ $2b$12$... or $argon2id$v=19$m=... │ │
│ └──────────────────────────────────────────────────┘ │
│ │
│ Verification: re-derive with stored salt/params, │
│ compare in constant time. │
└────────────────────────────────────────────────────────────┘
Algorithm Selection
┌────────────────────────────────────────────────────────────┐
│ CHOOSING AN ALGORITHM │
│ │
│ New project? │
│ → Argon2id (OWASP 1st tier) │
│ │
│ Need zero dependencies? │
│ → scrypt (built-in crypto) │
│ │
│ Legacy system or native builds blocked? │
│ → bcrypt (or bcryptjs) │
│ │
│ Any fast hash (SHA-256, MD5)? │
│ → Never. Not for passwords. │
└────────────────────────────────────────────────────────────┘
The 72-Byte Problem
┌────────────────────────────────────────────────────────────┐
│ bcrypt TRUNCATION │
│ │
│ Password: "correct horse battery staple" + "extra text" │
│ └────────── 72 bytes ──────────┘ │
│ │
│ bcrypt hashes only the first 72 bytes. │
│ Two passwords sharing the first 72 bytes collide. │
│ │
│ FIX: pre-hash with SHA-256 before bcrypt. │
│ sha256(password) → base64 → bcrypt.hash(digest, 12) │
│ │
│ Now any length is safe, and collisions are impossible. │
└────────────────────────────────────────────────────────────┘
Timing Attack Prevention
┌────────────────────────────────────────────────────────────┐
│ WHY timingSafeEqual MATTERS │
│ │
│ "abc" === "abd" → false (stops at byte 3) │
│ "abc" === "abc" → true (compares all 3) │
│ │
│ Attacker measures response time. │
│ Longer response → more bytes matched. │
│ Byte-by-byte recovery. │
│ │
│ timingSafeEqual always compares every byte. │
│ Response time is constant regardless of match position. │
└────────────────────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| bcrypt | Ubiquitous; CPU-bound; 72-byte limit |
| Argon2id | PHC winner; memory-hard; no input limit |
| scrypt | Built-in to Node; memory-hard |
| Pre-hashing | SHA-256 before bcrypt to bypass 72-byte limit |
| timingSafeEqual | Constant-time comparison for manual checks |
| OWASP Argon2id | m=19 MiB, t=2, p=1 |
| OWASP scrypt | N=2^17, r=8, p=1 |
| OWASP bcrypt | Cost 10+ |
| Rehashing | Upgrade parameters on successful login |
Key takeaways:
- Use Argon2id for new projects. It is memory-hard, has no input length limit, and is the OWASP first-tier recommendation.
- scrypt is a sound second choice. Node.js ships it in
cryptowith no npm dependency, though you must raisemaxmemfor OWASP parameters. - bcrypt remains acceptable but has a 72-byte limit. Pre-hash with SHA-256 to support longer passwords and avoid silent truncation collisions.
- Never compare hashes with
===. Use the library’scompare/verifymethod orcrypto.timingSafeEqualfor manual comparisons. - Rehash on login when parameters change. The only moment you have the plaintext is during a successful verification, so that is when to upgrade.
- Validate input before hashing. Reject multi-megabyte “passwords” before they reach the hashing function, which is expensive by design.
- Avoid sync hashing in servers.
hashSyncandscryptSyncblock the event loop. Use the async APIs.
Remember: Password hashing is the last line of defense when a database is compromised. The goal is to make each guess expensive. Argon2id is the modern default because it forces attackers to pay for memory, not just CPU. scrypt is built into Node.js and is a sound choice when dependencies are a concern. bcrypt is ubiquitous and acceptable if you handle its 72-byte limit with pre-hashing. In all cases, use a fresh random salt, store the parameters with the hash, compare in constant time, and rehash on login when parameters change. Never use SHA-256 or MD5 for passwords, and never store the plaintext.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!