Hashing, HMAC and randomness with crypto
createHash, createHmac, randomBytes and randomUUID, constant-time comparison with timingSafeEqual, AES-GCM encryption, and the Web Crypto API at a glance.
Hashing, HMAC and randomness with crypto
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- A hash such as SHA-256 turns any input into a fixed-size digest, one-way and deterministic. It proves integrity and identifies content. It is not encryption, and a plain fast hash is the wrong tool for storing passwords.
- An HMAC is a hash keyed with a secret. It proves that a message came from someone who knows the key and was not altered, which is how webhook signatures and signed cookies work. `createHmac('sha256', key).update(body).digest('hex')`.
- Compare secrets, signatures and tokens with `crypto.timingSafeEqual`, never `===`. It takes the same time whether the first byte or the last differs, and it throws if the lengths differ, so check the length first.
- Use `randomBytes`, `randomUUID` and `randomInt` for anything security-sensitive. `Math.random()` is predictable and must never generate tokens, session ids or keys.
- Authenticated encryption (AES-256-GCM) both hides the data and detects tampering: decryption throws if a single bit changed. A fresh random IV for every message is mandatory, and keys must come from secret storage, not source code.
What each tool is for
node:crypto wraps OpenSSL. Most of what an application needs fits in four jobs: fingerprint data (hashes), prove a message is genuine (HMAC), produce unpredictable values (random), and keep data secret (encryption). This lesson is about picking the right one. It was run on Node 26.13.1, which ships OpenSSL 4.1.
Hashing: a fingerprint
import { createHash, hash } from 'node:crypto';
createHash('sha256').update('hello').digest('hex');
// '2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824'
createHash('sha256').update('hel').update('lo').digest('base64url'); // same digest, incremental
hash('sha256', 'hello'); // one-shot helper, hex by default
A hash function maps any input to a fixed-size output. The same input always gives the same digest, a tiny change gives a completely different one, and you cannot go backwards. Use it to check that a download matches a published checksum, to detect whether a file changed, or to derive cache keys. update can be called repeatedly, which is how large files are hashed in chunks, and a hash object is a stream, so createReadStream(file).pipe(hash) works.
Two cautions. md5 and sha1 are broken for security uses; they are fine for non-adversarial checksums. And a hash is not a way to store passwords. A fast hash lets an attacker try billions of guesses per second. Passwords need a deliberately slow, salted function, and crypto.scrypt is built in; the practice is in password hashing and credential storage.
HMAC: a fingerprint only key-holders can make
If a webhook arrives saying “payment succeeded”, how do you know it came from the payment provider and not a stranger? A plain hash will not do, since a stranger can compute one too. An HMAC mixes a shared secret into the hash:
import { createHmac } from 'node:crypto';
const mac = createHmac('sha256', 'secret-key').update('payload').digest('hex');
Change the key or the payload and the output changes. The provider computes the HMAC of the body with the shared secret and sends it in a header, you recompute it and compare. Receiving and verifying webhooks covers the full pattern. Use the raw request body, not a re-serialized object, or the bytes will differ.
timingSafeEqual: comparing without leaking
Comparing the expected and received signature with === is a vulnerability. String comparison stops at the first different character, so a wrong guess that matches more leading characters takes slightly longer, and an attacker who can measure time can learn the signature a character at a time. timingSafeEqual takes the same time regardless:
import { createHmac, timingSafeEqual } from 'node:crypto';
function verify(body, signatureHex, key) {
const expected = createHmac('sha256', key).update(body).digest();
const given = Buffer.from(signatureHex, 'hex');
return given.length === expected.length && timingSafeEqual(given, expected);
}
verify('payload', mac, 'secret-key'); // true
verify('tampered', mac, 'secret-key'); // false
verify('payload', 'ab', 'secret-key'); // false (length check short-circuits)
timingSafeEqual throws ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH when the two buffers differ in length, so the length check comes first. That length is not secret. The buffers must be Buffers or typed arrays, which is why the hex string is converted with Buffer.from first.
Randomness
import { randomBytes, randomUUID, randomInt } from 'node:crypto';
randomBytes(16).toString('hex'); // 32 hex chars, a good session id or token
randomUUID(); // '3b241101-e2bb-4255-8caf-4136c566a962' style v4 UUID
randomInt(10); // 0..9 with no modulo bias
randomInt(5, 7); // 5 or 6
These draw from the operating system’s cryptographically secure generator. Math.random() does not: it is fast and predictable and must never produce tokens, passwords or keys. For randomInt, prefer it over Math.floor(Math.random() * n) in anything where fairness or unpredictability matters. With randomBytes, 16 bytes (128 bits) is plenty for a token. randomBytes and a callback form run on the thread pool, and the synchronous form is fine for small sizes (blocking vs non-blocking I/O).
Encryption, at a glance
Encrypting means you can get the data back with a key. Use authenticated encryption, which also detects tampering. AES-256-GCM is the default choice:
import { randomBytes, createCipheriv, createDecipheriv } from 'node:crypto';
const key = randomBytes(32); // in real code, load from a secret store
const iv = randomBytes(12); // new random IV for EVERY message
const c = createCipheriv('aes-256-gcm', key, iv);
const enc = Buffer.concat([c.update('top secret', 'utf8'), c.final()]);
const tag = c.getAuthTag();
const d = createDecipheriv('aes-256-gcm', key, iv);
d.setAuthTag(tag);
Buffer.concat([d.update(enc), d.final()]).toString(); // 'top secret'
Store the IV and tag with the ciphertext (they are not secret). Never reuse an IV with the same key. If you flip one byte of enc and decrypt, final() throws, which is the point: wrong ciphertext produces an error, not wrong data. Encryption does not solve key management: where the key lives is the hard part (secrets and sensitive data handling). Prefer well-built libraries or platform features for anything complicated, such as key exchange, certificates or signatures, and avoid designing protocols yourself.
Web Crypto
Node also exposes the browser’s crypto.subtle API as the global crypto. await crypto.subtle.digest('SHA-256', bytes) gives the same digest as the createHash call above, and crypto.randomUUID() works the same. Prefer it when you want code that runs in both a browser and Node.
What the video covers
This is NodeTLV 2023’s recording of Yonatan Mevorach’s talk “Mastering Cryptography Fundamentals with Node’s crypto module”, listed as English, advanced level, about 30 minutes. It works through the module’s building blocks with live Node code, per the event’s description. It is broader than this lesson and is a conference talk rather than a short explainer, so it is a length outlier in this roadmap. The same talk was recorded at Build Stuff in March 2025 (36 minutes), linked under “go deeper”. The timingSafeEqual pattern, webhook framing and the tamper test are in the prose, run on Node 26.13.1. No transcript was available.
Where this fits
You now have the primitives for signed webhooks, tokens and checksums. The last lesson in this group puts argument parsing, colour and exit codes together: building command-line tools.
Check yourself
Why is `createHash('sha256').update(password).digest('hex')` not an acceptable way to store passwords?
SHA-256 is designed to be fast, so an attacker with the stored digests can try billions of guesses per second, and identical passwords produce identical digests. Password storage needs a deliberately slow, salted function such as scrypt, argon2 or bcrypt. Node includes `scrypt` and `pbkdf2` in `crypto`, and the backend roadmap covers the practice.
What is the difference between a hash and an HMAC, and when do you need the second?
A hash has no secret, so anyone can compute it and it only checks integrity against a digest you trust. An HMAC mixes in a secret key, so only holders of the key can produce a valid one. Use an HMAC when you must prove who sent a message, such as verifying a webhook's signature.
What is wrong with `if (providedSignature === expectedSignature)` when verifying a signature?
String comparison stops at the first differing character, so response time leaks how many leading characters were right, and an attacker can recover a valid signature by timing guesses. Compare the raw bytes with `crypto.timingSafeEqual`, after checking that the lengths match, since it throws on different lengths.
You encrypt with AES-256-GCM and later flip one byte of the ciphertext. What happens on decryption?
`decipher.final()` throws (`bad decrypt` on this machine), because the authentication tag no longer matches. GCM is authenticated encryption, so tampering is detected instead of silently producing wrong plaintext.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.