Intermediate Node.js Interview QuestionsIntermediateConcept
Node.js · Question 58
What are the basics of the Node.js crypto module?
Direct answer
node:crypto provides hashing (createHash), HMAC, symmetric ciphers, random bytes, and key pairs — use for checksums, signed tokens, and encryption at rest; never roll custom crypto; passwords belong in bcrypt/argon2, not SHA256 alone.
The crypto module wraps OpenSSL — same primitives browsers lack natively in older Node-centric backends. AceDevHub uses it indirectly via JWT libraries and TLS termination.
| API | Use case |
|---|---|
| createHash('sha256') | File integrity, cache keys |
| createHmac('sha256', secret) | Webhook signature verification |
| randomBytes(n) | Session IDs, CSRF tokens |
| createCipheriv / createDecipheriv | AES-GCM encrypted fields |
| generateKeyPair | Asymmetric keys for signing |
- Timing attacks — compare HMACs with crypto.timingSafeEqual.
- Salt + slow hash — passwords: bcrypt/scrypt/argon2, not plain SHA256.
- IV uniqueness — never reuse IV/nonce with same key in GCM mode.
crypto-basics.mjs
import crypto from "node:crypto";
const hash = crypto.createHash("sha256").update("payload").digest("hex");
const secret = process.env.WEBHOOK_SECRET ?? "dev-secret";
const sig = crypto.createHmac("sha256", secret).update(body).digest("hex");
const token = crypto.randomBytes(32).toString("base64url");
// Verify webhook
const ok = crypto.timingSafeEqual(
Buffer.from(sig, "hex"),
Buffer.from(expected, "hex")
);