Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Node.js crypto: Hashing, HMAC, AES-GCM, and Random Bytes

Hashing, HMAC, AES-256-GCM and randomness solve different problems. Never reuse a GCM nonce, never hash a password with sha256, and compare secrets with timingSafeEqual.

~4 min readNode.js
#Node.js#Crypto#Security#Encryption
3D illustration of data flowing through a hash funnel into a digest cube beside an AES chamber and key tiles

Quick Summary

node:crypto covers four jobs that are easy to conflate: hashing (one-way digest), HMAC (digest keyed by a secret), symmetric encryption (AES-GCM, the right default), and randomness (randomBytes, randomUUID).

The blocking API is synchronous by default and uses the libuv threadpool for pbkdf2/scrypt, which matters on a busy server. The streaming API (createHash, createHmac, createCipheriv) exists for data larger than memory, and it is the only sane way to hash a upload stream.

Three rules prevent almost every real-world vulnerability in this module: a random 12-byte IV per AES-GCM message and never reuse one; passwords go through scrypt or pbkdf2 with calibrated cost, never a raw hash; and secrets are compared with timingSafeEqual, not ===.

Basic Syntax and Core Signatures

js
import { createHash, createHmac, timingSafeEqual, randomBytes, randomUUID, randomInt, createCipheriv, createDecipheriv, scrypt, pbkdf2, hkdf, generateKeyPairSync, sign, verify, hash, } from 'node:crypto'; import { promisify } from 'node:util'; const scryptP = promisify(scrypt); // Hashing createHash('sha256').update('data').digest('hex'); hash('sha256', 'data', 'hex'); // Node 20.12+ / 21.7+: one call const h = createHash('sha256'); h.copy(); // branch a hash mid-stream // HMAC and comparison const mac = createHmac('sha256', key).update(payload).digest(); timingSafeEqual(mac, expectedMac); // same length required // Random randomBytes(32); // Buffer, CSPRNG randomUUID(); // v4 randomInt(0, 100); // uniform, no modulo bias // AES-256-GCM const iv = randomBytes(12); const cipher = createCipheriv('aes-256-gcm', key, iv); cipher.setAAD(Buffer.from('user:42')); const ct = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]); const tag = cipher.getAuthTag(); // 16 bytes // store iv || tag || ct const decipher = createDecipheriv('aes-256-gcm', key, iv); decipher.setAAD(Buffer.from('user:42')); decipher.setAuthTag(tag); const pt = Buffer.concat([decipher.update(ct), decipher.final()]); // throws if tampered // Password KDF const salt = randomBytes(16); const derived = await scryptP('correct horse', salt, 64, { N: 16384, r: 8, p: 1, maxmem: 64 * 1024 * 1024 }); // Signing const { publicKey, privateKey } = generateKeyPairSync('ed25519'); const sig = sign(null, Buffer.from('msg'), privateKey); verify(null, Buffer.from('msg'), publicKey, sig); // true

Key Comparison Table

GoalPrimitiveWrong choiceWhy it fails
Integrity of datasha256/sha512md5, sha1Practical collisions
Authenticity with a shared secretcreateHmac('sha256', key)sha256(secret + msg)Length-extension attacks
Password storagescrypt / pbkdf2 (≥ 210k, sha512)sha256(password)Fast hashes are brute-forced on GPUs
Confidentialityaes-256-gcmaes-256-cbc without MACMalleable, padding oracles
Random tokensrandomBytesMath.random()Predictable PRNG
Comparing secretstimingSafeEqual===Timing side channel
KDFCost controlMemory-hardUse
scryptN, r, p, maxmemYesPassword hashing, default choice
pbkdf2iterationsNoFIPS contexts, legacy compatibility
hkdfNone (not a KDF for passwords)NoDeriving keys from a high-entropy secret
argon2External packageYesModern alternative outside core

Practical Edge Cases and Deep Dives

1. GCM nonce reuse destroys confidentiality and integrity

js
const iv = Buffer.alloc(12); // reused for every message const cipher = createCipheriv('aes-256-gcm', key, iv);

AES-GCM is catastrophically broken by a repeated IV under the same key: two ciphertexts under one nonce leak the XOR of the plaintexts, and the authentication key can be recovered, which lets an attacker forge messages. Generate randomBytes(12) per message and store it beside the ciphertext; 12 bytes is the size GCM is defined for (a 16-byte IV is hashed internally, which is slower and easy to misuse). For very high volume, use a counter plus a random per-session prefix rather than relying on random collision odds.

2. timingSafeEqual throws on different lengths

js
timingSafeEqual(Buffer.from('abc'), Buffer.from('abcd')); // ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH

The function compares byte by byte in constant time only when the lengths match, so a length check before it is unavoidable — and that check is itself a timing leak. The standard pattern hashes both sides first:

js
const a = createHash('sha256').update(given).digest(); const b = createHash('sha256').update(expected).digest(); const ok = timingSafeEqual(a, b);

Both digests are always 32 bytes, so the comparison is uniform. Comparing hex strings with === is the mistake this replaces: string comparison short-circuits at the first differing character, which is measurable over enough attempts.

3. scrypt parameters, maxmem, and the error it throws

js
await scryptP(password, salt, 64, { N: 32768, r: 8, p: 1 }); // Error: Invalid scrypt params

scrypt needs 128 * N * r bytes, so N = 32768, r = 8 wants 32 MiB — above the default maxmem of 32 MiB, and it throws rather than degrading. Pass maxmem explicitly and keep the derived key at 64 bytes: N = 16384 is the historical default, N = 65536 is a reasonable 2026 target on a server, and the value belongs in configuration so it can be raised as hardware improves. Store the parameters with each hash (scrypt$N$r$p$salt$hash), or old hashes cannot be verified after a change.

4. Streaming hashing for large inputs

js
import { createHash } from 'node:crypto'; import { createReadStream } from 'node:fs'; import { pipeline } from 'node:stream/promises'; const h = createHash('sha256'); await pipeline(createReadStream('image.iso'), async function* (source) { for await (const chunk of source) { h.update(chunk); yield chunk; } }); console.log(h.digest('hex'));

readFile then hash doubles peak memory and fails above the heap limit. The stream form keeps it at one chunk. For uploads, the same createHash instance can hash and write at once; the digest is only valid after the last chunk, so compute it in the end/pipeline completion, never inside the loop.

5. Keys, --env-file, and where secrets actually live

bash
node --env-file=.env app.js
js
const key = Buffer.from(process.env.DATA_KEY_B64, 'base64'); if (key.length !== 32) throw new Error('DATA_KEY_B64 must decode to 32 bytes');

A 32-byte AES-256 key is 44 base64 characters, and a truncated copy is a runtime error far from the cause — validate the length at startup. --env-file (Node 20.6+) removes the dotenv dependency but does not encrypt anything: keys in a .env on disk are readable by the process user and visible in a container image layer. For anything long-lived, a KMS/secret manager or an env var injected at runtime is the difference between a leak and an incident.

6. node:crypto versus WebCrypto

js
import { webcrypto } from 'node:crypto'; const { subtle } = webcrypto; const key = await subtle.importKey('raw', raw, { name: 'AES-GCM' }, false, ['encrypt']);

The subtle API is asynchronous, standards-aligned, and portable to browsers and edge runtimes, which makes it the better choice for code that also runs in a Worker or at the edge. It is also narrower: no scrypt, no streaming hash, and key material is opaque after import. Node's own module stays necessary for scrypt, pbkdf2 with large iteration counts, streaming hashes, and OpenSSL-backed signing of big payloads.

Common Node.js Runtime Mistakes

SymptomCauseFix
ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTHBuffers of different lengthHash both to 32 bytes first
decipher.final() throws Unsupported state or unable to authenticate dataTampered ciphertext, wrong key, or wrong AADVerify key/AAD, treat as an attack
Invalid scrypt params128 * N * r above maxmemRaise maxmem, or lower N
Tokens recoverable in practiceMath.random() for secretsrandomBytes, randomUUID
Two ciphertexts with the same IVStatic nonceRandom 12-byte IV per message
createCipher not a functionRemoved APIcreateCipheriv with an explicit IV
Hash mismatch on large uploadsdigest() called mid-streamDigest after the last chunk
ERR_OSSL_EVP_UNSUPPORTED in a containerOld OpenSSL, e.g. md4, rc4Use a modern cipher
Slow login endpoint under loadscryptSync in a request handlerAsync scrypt (threadpool)

Try matching browser tools

All tools

Small utilities that fit Node.js work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Node.js guides

More in Node.js

All Node.js guides

The guides filed next to this one in Node.js, in library order.