Summary - Crypto
- Node.js course
- Intermediate
- Lesson 105/116
- 5 min
Combine createHash, randomBytes and HMAC to write an encryptor.
Summary - Crypto
In this group you learned Node.js's crypto module: one-way hashes with createHash, secure random bytes with randomBytes, keyed signatures with createHmac, AES encryption with createCipheriv. Now we will combine them in an encryptor.
Structure: hash a string with createHash, generate a salt with randomBytes, sign with createHmac. We verify each tool works correctly by printing the length of its output. This is the foundation of a real authentication system: hashes give fingerprints, salts give uniqueness, HMAC gives signatures. Since output lengths are fixed, we get deterministic results when combining them.
Practice Write an encryptor helper
Import with const crypto = require("node:crypto");. Hash with const hash = crypto.createHash("sha256").update("merhaba").digest("hex");. Generate salt with const salt = crypto.randomBytes(4).toString("hex");. Sign with const hmac = crypto.createHmac("sha256", "anahtar").update("veri").digest("hex");. Print lengths with console.log("Hash length: " + hash.length), console.log("Salt length: " + salt.length) and console.log("HMAC length: " + hmac.length).
Starter code
// Import the crypto module
// write here
// Hash "merhaba"
// write here
// Generate 4-byte salt
// write here
// Sign "veri" with HMAC
// write here
// Print three lengths
// write hereSample solution
const crypto = require("node:crypto");
const hash = crypto.createHash("sha256").update("merhaba").digest("hex");
const salt = crypto.randomBytes(4).toString("hex");
const hmac = crypto.createHmac("sha256", "anahtar").update("veri").digest("hex");
console.log("Hash length: " + hash.length);
console.log("Salt length: " + salt.length);
console.log("HMAC length: " + hmac.length);Expected output
Hash uzunluğu: 64 Tuz uzunluğu: 8 HMAC uzunluğu: 64
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the correct way to store a password safely?
Parola → hash → sakla- Storing it as plain text
- Encoding with Base64 and storing it
- Tuz ile hash'leyip saklamak Correct answer
- Only printing with console.log
Explanation: Hashing with salt is the safest way to store.
2 Match each tool to its purpose
| Term | Meaning |
|---|---|
createHash |
One-way hash |
randomBytes |
Secure random bytes |
createHmac |
Keyed signature |
createCipheriv |
Two-way encryption |
3 Complete the createHash call
const hash = crypto.____("sha256").update("merhaba").digest("hex");
const hash = crypto.createHash("sha256").update("merhaba").digest("hex");
Explanation: createHash with sha256 creates a hash.