Node.js Crypto
The node:crypto module provides hashing, message authentication, encryption, key derivation and secure random values — all backed by OpenSSL. You'll use it to store passwords safely, sign webhooks, verify downloads and generate tokens.
const crypto = require('node:crypto'); // CommonJS
import crypto from 'node:crypto'; // ES modulesWhat's inside
| Task | Function |
|---|---|
| Fingerprint data | createHash('sha256') |
| Sign/verify with a shared secret | createHmac('sha256', key) |
| Hash a password | scrypt / scryptSync, pbkdf2 |
| Encrypt/decrypt | createCipheriv / createDecipheriv |
| Random bytes / IDs | randomBytes(n), randomUUID(), randomInt(min, max) |
| Constant-time compare | timingSafeEqual(a, b) |
Hashing
A hash function turns any input into a fixed-size digest. The same input always produces the same digest, and a tiny change produces a completely different one. Hashes can't be reversed.
const { createHash } = require('node:crypto');
const sha256 = (text) => createHash('sha256').update(text).digest('hex');
console.log(sha256('hello'));
console.log(sha256('hello!'));
console.log(createHash('md5').update('hello').digest('hex'));
console.log(createHash('sha1').update('hello').digest('base64'));2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
ce06092fb948d9ffac7d1a376e404b26b7575bcc11ee05a4615fef4fec3a308b
5d41402abc4b2a76b9719d911017c592
qvTGHdzF6KLavt4PO0gs2a6pQ00=
You can call update() several times (for example once per chunk of a file) before calling digest(). digest() takes an encoding: 'hex', 'base64', 'base64url', or nothing for a Buffer.
Note: MD5 and SHA-1 are broken for security purposes. They're fine as checksums for detecting accidental corruption, but use SHA-256 or better for anything security-related.
Since Node 21.7 there is also a one-shot shortcut: crypto.hash('sha256', 'hello').
HMAC: proving a message wasn't tampered with
An HMAC is a hash mixed with a secret key. Services like GitHub and Stripe sign webhook bodies this way; your server recomputes the HMAC and compares:
const { createHmac, timingSafeEqual } = require('node:crypto');
const secret = 'webhook-secret';
const body = '{"event":"order.paid","id":42}';
const signature = createHmac('sha256', secret).update(body).digest('hex');
console.log('signature:', signature);
function verify(body, received) {
const expected = createHmac('sha256', secret).update(body).digest();
const given = Buffer.from(received, 'hex');
return given.length === expected.length && timingSafeEqual(given, expected);
}
console.log('valid :', verify(body, signature));
console.log('tampered :', verify(body.replace('42', '43'), signature));signature: 1cf28dec921b2b0caddfcf5438efeb87d7f5b44f80c8523b6ec7c601711337cc
valid : true
tampered : false
timingSafeEqual always takes the same time regardless of where the first difference is, so attackers can't guess the signature byte by byte by measuring response times.
Hashing passwords
Never store passwords with a plain SHA-256 — fast hashes can be brute-forced at billions of guesses per second. Use a slow, salted key-derivation function such as scrypt. The salt is random in real code; here it's fixed so the output is repeatable:
const { scryptSync, timingSafeEqual } = require('node:crypto');
function hashPassword(password, salt) {
const key = scryptSync(password, salt, 32);
return `${salt}:${key.toString('hex')}`;
}
function checkPassword(password, stored) {
const [salt, hex] = stored.split(':');
const key = scryptSync(password, salt, 32);
return timingSafeEqual(key, Buffer.from(hex, 'hex'));
}
const stored = hashPassword('correct horse', 'c0ffee1234');
console.log(stored);
console.log(checkPassword('correct horse', stored));
console.log(checkPassword('wrong guess', stored));c0ffee1234:5937dc942e6226268151cbd443b88499d4c29934b725d58e2e2ea73da7271217
true
false
In a real application create the salt with crypto.randomBytes(16).toString('hex') and store it next to the hash.
Encrypting and decrypting
Hashing is one-way; encryption is reversible with the key. AES-256-GCM is a good modern default: it encrypts and detects tampering through an authentication tag. The key and IV below are fixed for the demo; in practice the IV must be unique for every message.
const crypto = require('node:crypto');
const key = crypto.scryptSync('my passphrase', 'demo-salt', 32); // 32 bytes = AES-256
const iv = Buffer.alloc(12, 1); // demo only!
function encrypt(text) {
const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
const data = Buffer.concat([cipher.update(text, 'utf8'), cipher.final()]);
return { data, tag: cipher.getAuthTag() };
}
function decrypt({ data, tag }) {
const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
decipher.setAuthTag(tag);
return Buffer.concat([decipher.update(data), decipher.final()]).toString('utf8');
}
const box = encrypt('meet at noon');
console.log('ciphertext bytes:', box.data.length);
console.log('decrypted :', decrypt(box));
box.data[0] ^= 1; // flip one bit
try {
decrypt(box);
} catch (err) {
console.log('tampered :', err.message);
}ciphertext bytes: 12
decrypted : meet at noon
tampered : Unsupported state or unable to authenticate data
Random values
For tokens, session IDs and salts use the crypto module — never Math.random(), which is predictable:
crypto.randomUUID(); // e.g. '3b241101-e2bb-4255-8caf-4136c566a962'
crypto.randomBytes(32).toString('hex');
crypto.randomInt(1, 7); // a fair die roll, 1–6Test yourself
Which statement about hashes is true?
- They can be decrypted with the right key
- The same input always gives the same digest
- Their length depends on the input length
- MD5 is recommended for passwords
What should you use to store user passwords?
- sha256(password)
- Base64 encoding
- A slow salted KDF like scrypt
- AES encryption with a fixed key
Why compare signatures with timingSafeEqual instead of ===?
- It is faster
- It works with strings
- Its running time doesn't reveal where the values differ
- It ignores case