Node.js Crypto Module
The crypto module protects data. It creates fingerprints of data, generates random values, signs messages, and locks secret text. Banks, chat apps, and login systems rely on these tools.
Load the Module
const crypto = require("crypto");Crypto ships with Node.js. You install nothing.
Hashing: A Fingerprint for Data
A hash turns any text into a fixed-length code. Think of it as a fingerprint. The same text always gives the same fingerprint. A different text gives a different one. Nobody can rebuild the original text from the fingerprint.
"hello" --> [ SHA-256 ] --> 2cf24dba5fb0a30e... "hello!" --> [ SHA-256 ] --> ce06092fb948d9ff... Small change in text = completely new fingerprint
const hash = crypto
.createHash("sha256")
.update("hello")
.digest("hex");
console.log(hash);Where Hashes Help
- Check that a downloaded file stayed unchanged.
- Create short keys for caching.
- Detect duplicate files.
Choose SHA-256 or stronger. Skip MD5 and SHA-1, since experts consider them weak.
HMAC: A Fingerprint with a Secret Key
HMAC mixes a secret key into the hash. Only people who know the key can create the correct fingerprint. Servers use HMAC to confirm that a message came from a trusted sender.
const signature = crypto
.createHmac("sha256", "my-secret-key")
.update("order=1001&amount=500")
.digest("hex");
console.log(signature);
Sender: message + secret key --> signature
Receiver: message + same key --> new signature
Both signatures match? The message is genuine.
Random Values
Security needs unpredictable values. The Math.random function is not safe for this job. Use the crypto functions instead.
console.log(crypto.randomBytes(16).toString("hex")); // random token
console.log(crypto.randomUUID()); // unique id
console.log(crypto.randomInt(100000, 999999)); // six-digit codeUse these values for reset links, session tokens, and one-time codes.
Encryption: A Lock and Key for Text
Encryption scrambles text so only a key holder can read it. Decryption reverses the process. AES-256-GCM is a strong, popular method.
Plain text --> [ Encrypt + Key ] --> Scrambled text Scrambled --> [ Decrypt + Key ] --> Plain text
const key = crypto.randomBytes(32);
const iv = crypto.randomBytes(12);
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(box) {
const decipher = crypto.createDecipheriv("aes-256-gcm", key, iv);
decipher.setAuthTag(box.tag);
return Buffer.concat([decipher.update(box.data), decipher.final()]).toString("utf8");
}
const secret = encrypt("Meet at 5 PM");
console.log(decrypt(secret)); // Meet at 5 PMKey Words to Know
- Key is the secret that locks and unlocks the data.
- IV is a random starter value. Create a new IV for every message.
- Auth tag proves nobody changed the scrambled data.
Compare Secrets Safely
A normal comparison can leak timing clues. Use timingSafeEqual to compare signatures and tokens.
const a = Buffer.from("abc123");
const b = Buffer.from("abc123");
console.log(crypto.timingSafeEqual(a, b)); // trueBoth buffers need the same length, or the function throws an error.
Safe Habits
- Store keys in environment variables, never inside your code.
- Rotate keys on a regular schedule.
- Rely on proven algorithms and avoid inventing your own.
- Keep Node.js updated to receive security fixes.
Practice Tasks
- Hash two similar sentences and compare the outputs.
- Generate a six-digit code with randomInt.
- Sign a short message with HMAC and verify it with a second HMAC call.
