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.

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
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); // trueKey Comparison Table
| Goal | Primitive | Wrong choice | Why it fails |
|---|---|---|---|
| Integrity of data | sha256/sha512 | md5, sha1 | Practical collisions |
| Authenticity with a shared secret | createHmac('sha256', key) | sha256(secret + msg) | Length-extension attacks |
| Password storage | scrypt / pbkdf2 (≥ 210k, sha512) | sha256(password) | Fast hashes are brute-forced on GPUs |
| Confidentiality | aes-256-gcm | aes-256-cbc without MAC | Malleable, padding oracles |
| Random tokens | randomBytes | Math.random() | Predictable PRNG |
| Comparing secrets | timingSafeEqual | === | Timing side channel |
| KDF | Cost control | Memory-hard | Use |
|---|---|---|---|
scrypt | N, r, p, maxmem | Yes | Password hashing, default choice |
pbkdf2 | iterations | No | FIPS contexts, legacy compatibility |
hkdf | None (not a KDF for passwords) | No | Deriving keys from a high-entropy secret |
argon2 | External package | Yes | Modern alternative outside core |
Practical Edge Cases and Deep Dives
1. GCM nonce reuse destroys confidentiality and integrity
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
timingSafeEqual(Buffer.from('abc'), Buffer.from('abcd')); // ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTHThe 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:
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
await scryptP(password, salt, 64, { N: 32768, r: 8, p: 1 }); // Error: Invalid scrypt paramsscrypt 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
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
node --env-file=.env app.jsconst 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
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
| Symptom | Cause | Fix |
|---|---|---|
ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH | Buffers of different length | Hash both to 32 bytes first |
decipher.final() throws Unsupported state or unable to authenticate data | Tampered ciphertext, wrong key, or wrong AAD | Verify key/AAD, treat as an attack |
Invalid scrypt params | 128 * N * r above maxmem | Raise maxmem, or lower N |
| Tokens recoverable in practice | Math.random() for secrets | randomBytes, randomUUID |
| Two ciphertexts with the same IV | Static nonce | Random 12-byte IV per message |
createCipher not a function | Removed API | createCipheriv with an explicit IV |
| Hash mismatch on large uploads | digest() called mid-stream | Digest after the last chunk |
ERR_OSSL_EVP_UNSUPPORTED in a container | Old OpenSSL, e.g. md4, rc4 | Use a modern cipher |
| Slow login endpoint under load | scryptSync in a request handler | Async scrypt (threadpool) |
Try matching browser tools
All toolsSmall utilities that fit Node.js work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Node.js guides
All Node.js guidesNode.js EventEmitter: once, error Events, and Listener Memory Leaks
emit is synchronous, so a throwing listener aborts the rest. An error event with no listener crashes the process, and a listener per request is the classic leak.
Node.js fs/promises: Read, Write, Watch, and Atomic File Operations
writeFile truncates before writing, so a crash leaves half a file. The atomic pattern is temp file, fsync, rename; readFile loads everything, so large files need streams.
Node.js Streams: Readable, Writable, Transform, and pipeline
pipe() forwards data but not errors; pipeline() destroys the chain and rejects. Backpressure is the false return from write(), and _flush that never calls back hangs forever.
Node.js Buffer and TypedArray: Encodings and Binary Manipulation
A Buffer is a view over an ArrayBuffer, so byteLength is not string length and toString can silently corrupt split UTF-8. allocUnsafe and pooled buffers carry old data.
More in Node.js
All Node.js guidesThe guides filed next to this one in Node.js, in library order.