Node.js Crypto and Secrets, Done Right with node:crypto
· Security · by Sal Anvarov
A walkthrough of password hashing, secure tokens, JWT verification, AES-GCM encryption and secret handling in Node.js using only the built-in crypto module, with tests that show each mistake and each fix.
Most crypto bugs I see in Node.js code aren't exotic. Nobody is breaking AES. They are the same handful of small mistakes, made again and again:
- Passwords stored as
sha256(password), fast and unsalted. - Reset links and session IDs built from
Math.random(). - Signatures and hashes compared with
===. - JWT verifiers that let the token pick its own algorithm, including
none. - AES with a fixed IV and no integrity check.
- Secrets hardcoded with a
"changeme"default, or printed straight into logs.
Each of these looks fine in a code review and passes every functional test. The app works. It just isn't safe.
So I built nodejs-crypto-secrets, the fourth repo in my Node.js security series. It has zero dependencies and uses nothing but node:crypto. Each file in src/ puts the common mistake right next to the fix, and the test file proves the difference. For example, it forges an alg: none JWT and shows the unsafe verifier accepting it.
One warning before we start: every function that ends in Unsafe is vulnerable on purpose, so the tests can show the attack working. Copy the safe versions, never those.
The layout
src/
password.js sha256 vs salted scrypt
tokens.js Math.random vs crypto.randomBytes
jwt.js alg-trusting verifier vs pinned HS256
encrypt.js AES-CBC with static IV vs AES-256-GCM
config.js fail-fast secret loading and log redaction
test/
crypto.test.js proves each mistake and each fix
Five topics, five small files. Let's go through them in order.
1. Password storage
The mistake
export const hashPasswordUnsafe = (password) => createHash('sha256').update(password).digest('hex');
SHA-256 is a great hash. It is also built to be fast, and that is exactly the wrong property for passwords. If your users table leaks, an attacker with a GPU can try a huge number of guesses per second against it. With no salt, two users with the same password get the same hash, so one cracked hash cracks all of them, and precomputed tables work too.
The fix
// SAFE: scrypt is deliberately slow and memory-hard, with a random salt per user.
// N=2^15, r=8 uses 32 MiB and ~50-100 ms per hash. Raise N as hardware gets faster.
const PARAMS = { N: 2 ** 15, r: 8, p: 1, maxmem: 64 * 1024 * 1024 };
const KEY_LEN = 64;
// Parameters are stored with the hash so you can raise them later and still
// verify old hashes.
export async function hashPassword(password) {
const salt = randomBytes(16);
const key = await scryptAsync(password.normalize('NFKC'), salt, KEY_LEN, PARAMS);
return ['scrypt', PARAMS.N, PARAMS.r, PARAMS.p, salt.toString('base64'), key.toString('base64')].join('#x27;);
}
There are a few deliberate choices in here.
scrypt instead of SHA. scrypt is built into Node and is memory-hard: each hash needs a block of RAM, not just CPU time. Its memory cost is roughly 128 * N * r bytes, so N = 2^15, r = 8 comes out to 32 MiB. That is the "32 MiB" in the comment. GPUs and custom hardware get much less of a speedup when every guess needs that much memory. Argon2id and bcrypt are also fine choices. The point is "slow and purpose-built", not "scrypt specifically".
maxmem. Node's scrypt refuses to run if the memory it needs is above maxmem. The default limit is 32 MiB, and these parameters land just over it, so with the default you get a "memory limit exceeded" error. That is why the code sets maxmem to 64 MiB. If you raise N later, raise maxmem along with it, or hashing will throw.
A 16-byte random salt per user. The salt makes every hash unique, even for identical passwords, which kills precomputed tables and "crack one, crack all".
Parameters stored with the hash. The output looks like scrypt$32768$8$1lt;salt>lt;hash>. When you raise the cost later, old hashes still verify with their own parameters, and you can rehash on the user's next successful login.
NFKC normalization. The same password typed on two different keyboards can produce different Unicode byte sequences. Normalizing first means the user can still log in.
On tuning: OWASP's Password Storage Cheat Sheet suggests a higher scrypt cost (N = 2^17) as its minimum, and the repo's comment says to raise N as hardware gets faster. Measure on your own servers and pick the highest cost your login latency budget allows.
Verification re-derives the key with the stored parameters and compares in constant time:
// Constant time: `===` stops at the first differing byte, which leaks timing.
return timingSafeEqual(key, expected);
timingSafeEqual throws if the two Buffers differ in length. Here that can't happen, because the key is derived with expected.length as its output length. It also returns false early for any stored value that doesn't start with scrypt, so an old md5$... row can't sneak through.
One thing a strong hash does not do: stop online guessing. You still need rate limiting and lockouts on the login endpoint.
2. Random tokens
The mistake
// UNSAFE: Math.random is not cryptographically secure. V8's generator state can
// be recovered from a handful of outputs, and then every future token predicted.
export const resetTokenUnsafe = () => Math.random().toString(36).slice(2);
Math.random() is fine for shuffling a playlist. It was never meant to resist an attacker. If someone can see a few of its outputs, they can work out its internal state and predict the next ones, including the password reset link you are about to email to someone else.
The fix
// SAFE: 32 bytes from the OS CSPRNG (256 bits), URL-safe.
export const resetToken = () => randomBytes(32).toString('base64url');
// SAFE: uniform 6-digit code. `randomBytes(n) % 1e6` would be slightly biased.
export const otpCode = () => String(randomInt(0, 1_000_000)).padStart(6, '0');
export const sessionId = () => randomUUID();
Why these choices:
- 32 bytes is 256 bits. Nobody is going to guess that.
base64urlmakes it safe to drop into a URL without escaping, and it comes out to exactly 43 characters. randomIntfor OTP codes. Taking random bytes modulo one million looks right but isn't quite uniform, because the range of the random number usually isn't an exact multiple of a million.randomInthandles that properly.padStartkeeps leading zeros, so004213stays six digits.randomUUIDis a version 4 UUID from the same secure generator, which is a convenient session ID format.
The second half of the fix is easy to skip:
// Store only a hash of reset/API tokens, like passwords. If the database leaks,
// the tokens can't be used. A fast hash is fine here because the token is
// random and long, so there is nothing to brute force.
export const hashToken = (token) => createHash('sha256').update(token).digest('hex');
Treat reset tokens and API keys like passwords: store a hash, not the token. Unlike passwords, a fast hash is the right choice here. A slow hash protects low-entropy human input. A 256-bit random token has nothing to brute force, so SHA-256 is enough. Also make reset tokens single use and short lived; the README suggests 15 to 60 minutes.
3. JWT verification
This is the section with the most dramatic test, so it's my favorite.
The mistake
// UNSAFE: trusts the token's own header to pick the algorithm. A token with
// {"alg":"none"} and no signature is accepted. Also ignores `exp`, and `!==`
// on strings leaks timing.
export function verifyUnsafe(token, secret) {
const [header, body, sig] = token.split('.');
if (decode(header).alg === 'none') return decode(body);
if (sig !== hmac(`${header}.${body}`, secret).toString('base64url')) throw new Error('bad signature');
return decode(body);
}
The JWT header is attacker-controlled input. It's just base64. If the verifier reads alg from the token and does what it says, the attacker gets to choose how the token is checked. alg: none means "no signature", so a forged token with any payload sails through. This is a well-known class of JWT bug, and the same idea underlies algorithm confusion attacks, where a token switches from an asymmetric algorithm to HMAC.
This verifier has two more problems. It never checks exp, so a stolen token works forever. And it compares signatures with !==, which can return as soon as one character differs.
The fix
// SAFE: the server decides the algorithm, compares in constant time, and
// enforces expiry.
export function verify(token, secret) {
const parts = token.split('.');
if (parts.length !== 3) throw new Error('malformed token');
const [header, body, sig] = parts;
if (decode(header).alg !== 'HS256') throw new Error('unexpected algorithm');
const expected = hmac(`${header}.${body}`, secret);
const given = Buffer.from(sig, 'base64url');
if (given.length !== expected.length || !timingSafeEqual(given, expected)) throw new Error('bad signature');
const payload = decode(body);
if (typeof payload.exp !== 'number' || payload.exp <= Date.now() / 1000) throw new Error('token expired');
return payload;
}
Line by line:
- Structure check. Exactly three parts, or it's rejected.
- The algorithm is pinned. The server only accepts
HS256. The header is checked against that, not obeyed. - The signature is always recomputed over the exact
header.bodybytes, then compared as raw bytes withtimingSafeEqual. The length check comes first, becausetimingSafeEqualthrows on Buffers of different lengths. - Expiry is required. A missing or non-numeric
expis rejected, not treated as "never expires". The matchingsignfunction always setsexp, with a 15-minute default.
The file says this plainly: it is a minimal HS256 implementation to show which checks a verifier has to make. In production, use a maintained library like jose and still pin the algorithm:
jwtVerify(token, key, { algorithms: ['HS256'] })
A few more rules from the README that I follow everywhere:
- HS256 secrets must be long and random (32+ bytes), not a human password.
- Check
issandaudtoo once more than one service is involved. - Prefer asymmetric keys (ES256 or EdDSA) when other services need to verify tokens but shouldn't be able to issue them.
- JWTs can't be revoked before they expire, so keep them short lived.
- The payload is only base64, not encrypted. Don't put secrets in it.
4. Encrypting data
The mistake
// UNSAFE: CBC with a fixed IV and no authentication. The same plaintext always
// gives the same ciphertext (leaks equality), and an attacker can flip bits in
// the ciphertext without you noticing.
const STATIC_IV = Buffer.alloc(16, 0);
export function encryptUnsafe(plaintext, key) {
const cipher = createCipheriv('aes-256-cbc', key, STATIC_IV);
return Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]).toString('base64');
}
Two separate problems. A fixed IV makes encryption deterministic: encrypt the same value twice and you get the same ciphertext, so anyone reading the database can tell which rows hold equal values. And CBC on its own only gives confidentiality, not integrity. An attacker who can modify the ciphertext can change the decrypted result, and nothing in your code will notice.
The fix
// SAFE: AES-256-GCM. Fresh random 12-byte IV per message, and a 16-byte auth
// tag so any tampering makes decryption throw.
// Output layout: iv (12) | tag (16) | ciphertext, base64 encoded.
const IV_LEN = 12;
const TAG_LEN = 16;
export function encrypt(plaintext, key) {
const iv = randomBytes(IV_LEN);
const cipher = createCipheriv('aes-256-gcm', key, iv, { authTagLength: TAG_LEN });
const ciphertext = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);
return Buffer.concat([iv, cipher.getAuthTag(), ciphertext]).toString('base64');
}
AES-256-GCM is an AEAD mode: authenticated encryption. Along with the ciphertext it produces an authentication tag, and decryption fails if a single bit of the IV, tag or ciphertext has changed. ChaCha20-Poly1305 is the other common AEAD choice.
A 12-byte (96-bit) IV is the standard IV size for GCM, the one NIST SP 800-38D treats as the default. The IV doesn't have to be secret, so it is stored right in front of the ciphertext.
A fresh random IV for every message is not optional with GCM. Reusing an IV with the same key is catastrophic: it leaks the XOR of the two plaintexts and lets an attacker forge tags. With random 96-bit IVs, the usual guidance is to stay under about 2^32 messages per key, then rotate the key.
The full 16-byte tag, passed explicitly as authTagLength on both sides. Decryption sets the expected tag length too, so a truncated tag gets rejected instead of quietly accepted:
export function decrypt(blob, key) {
const buf = Buffer.from(blob, 'base64');
const decipher = createDecipheriv('aes-256-gcm', key, buf.subarray(0, IV_LEN), { authTagLength: TAG_LEN });
decipher.setAuthTag(buf.subarray(IV_LEN, IV_LEN + TAG_LEN));
return Buffer.concat([decipher.update(buf.subarray(IV_LEN + TAG_LEN)), decipher.final()]).toString('utf8');
}
The tag check happens in decipher.final(). If anything was tampered with, that call throws, and no plaintext is returned.
The key itself should come from a secret manager or KMS, never from source code. For anything serious, use envelope encryption: encrypt your data keys with a KMS master key.
5. Secrets and config
The last file is the least "crypto" and probably the one that matters most day to day.
Fail fast on missing or weak secrets
export function requireSecret(name, { minBytes = 32, env = process.env } = {}) {
const value = env[name];
if (!value) throw new Error(`Missing required secret: ${name}`);
const bytes = Buffer.from(value, 'base64');
if (bytes.length < minBytes) {
throw new Error(`${name} must be at least ${minBytes} random bytes, base64 encoded. Generate one with:\n` +
` node -e "console.log(crypto.randomBytes(${minBytes}).toString('base64'))"`);
}
return bytes;
}
No fallback values. If JWT_SECRET is missing, the app refuses to start. That beats finding out at 3am that production has been signing tokens with "changeme" for a month. The secret has to decode to at least 32 bytes, and the error message tells you exactly how to generate one. The env option exists so tests can pass a fake environment.
Locally, Node can load the file itself with node --env-file=.env app.js. Keep .env in .gitignore. In production, inject the variables from your platform's secret manager.
Redact before logging
// Use when logging config or request data, so secrets never end up in logs.
const SECRET_KEY = /pass(word)?|secret|token|api[-_]?key|authorization|cookie/i;
export function redact(obj) {
return JSON.parse(JSON.stringify(obj, (key, value) => (SECRET_KEY.test(key) ? '[REDACTED]' : value)));
}
The JSON.stringify replacer walks every nested key, so headers.Authorization gets caught as well as password at the top level. The output is a fresh copy, so the original object isn't changed. Never log request headers, bodies or process.env without something like this in front of them.
And if a secret was ever committed to git, rotate it. Removing it from the history isn't enough.
How the tests prove it
All six tests live in test/crypto.test.js and use the built-in node:test runner. Each one shows the unsafe behavior and then the safe one.
| Test | What it proves |
|---|---|
| Passwords | sha256 gives identical hashes for identical passwords. Two scrypt hashes of the same password differ, match the scrypt$32768$8$1$ format, verify correctly, reject a wrong password, and reject an md5$... record. |
| Tokens | 1,000 reset tokens are all unique and each matches ^[A-Za-z0-9_-]{43}$. The token hash is stable and differs from the token. OTP codes are exactly six digits. |
| JWT forgery | A hand-built alg: none token claiming role: 'admin' is accepted by verifyUnsafe and rejected by verify with "unexpected algorithm". |
| JWT checks | A valid token verifies. A tampered payload, a wrong key, an expired token and a two-part token all throw. |
| Encryption | CBC with a static IV gives identical ciphertexts for identical input. GCM gives different ciphertexts each time, round-trips correctly, and throws when a single bit is flipped or the wrong key is used. |
| Config | A missing secret and a "changeme" secret both throw. A 32-byte random secret loads. redact hides password, a nested Authorization header and apiKey, and leaves user alone. |
Here is the forgery test, because it's the clearest demo of the whole repo:
test('JWT: forged alg=none token fools the unsafe verifier only', () => {
const secret = randomBytes(32);
const b64 = (o) => Buffer.from(JSON.stringify(o)).toString('base64url');
const forged = `${b64({ alg: 'none' })}.${b64({ sub: 'attacker', role: 'admin' })}.`;
assert.equal(verifyUnsafe(forged, secret).role, 'admin');
assert.throws(() => verify(forged, secret), /unexpected algorithm/);
});
No secret, no signature, admin access, at least with the unsafe verifier.
Running it
You need Node.js 22.13 or newer. There's nothing to install:
git clone https://github.com/msanvarov/nodejs-crypto-secrets.git
cd nodejs-crypto-secrets
npm test
npm test just runs node --test. When I run it, all six tests pass. The password test is by far the slowest of the six, which is the point: scrypt is supposed to be expensive. CI runs the same command on Node 22 and 24 for every push and pull request.
Takeaways
- Hash passwords with scrypt, Argon2id or bcrypt, with a random salt per user. Never a bare SHA or MD5.
- Store the cost parameters with each hash, so you can raise them and rehash on login.
- Rate limit logins. A slow hash doesn't stop online guessing.
- Generate tokens with
randomBytes,randomIntorrandomUUID. NeverMath.random. - Store only a hash of reset tokens and API keys. Make reset tokens single use and short lived.
- Compare secrets with
timingSafeEqualon equal-length Buffers, not===. - Pin the JWT algorithm on the server, always require
exp, and use a maintained library likejose. - Use AES-256-GCM (or ChaCha20-Poly1305) with a fresh random 12-byte IV per message and a full 16-byte tag.
- Never reuse an IV with the same GCM key, and rotate keys well before about 2^32 messages.
- Load secrets from the environment, fail fast if they're missing or short, and keep keys in a secret manager or KMS.
- Redact secrets before anything reaches your logs, and rotate any secret that was ever committed.
The full code, tests and guidance are on GitHub: msanvarov/nodejs-crypto-secrets. If you spot a mistake or want to add an example, issues and pull requests are welcome.