Node.js
/Intermediate
Crypto Module
Definition
A core module that provides cryptographic functionality that includes a set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify functions.
Explain Like I'm New
The security vault of Node.js. It gives you the tools to securely hash passwords so hackers can't read them, generate random secure tokens for resetting passwords, and encrypt sensitive data like credit card numbers.
Real World Example
Creating a unique, un-guessable ID for a user's session token using `crypto.randomUUID()`.
Common Use Cases
- •Password hashing (though bcrypt is preferred)
- •Generating secure random strings
- •Data encryption/decryption
Terminal Output
bash / terminal
const crypto = require('crypto');
// 1. Generate a secure Random UUID
const newUserId = crypto.randomUUID();
console.log("UUID:", newUserId);
// 2. Generate cryptographically secure random bytes (Great for API keys)
const apiKey = crypto.randomBytes(32).toString('hex');
console.log("API Key:", apiKey);
// 3. Hashing Data (One-way scramble)
// We hash a string using the SHA-256 algorithm
const secretMessage = "My Super Secret Password";
const hash = crypto.createHash('sha256').update(secretMessage).digest('hex');
console.log("Original:", secretMessage);
console.log("SHA-256 Hash:", hash);
// If even ONE letter changes, the hash changes completely.
const hash2 = crypto.createHash('sha256').update("My Super Secret Password!").digest('hex');
console.log("Changed Hash:", hash2);
Interview Questions
basic
- How do you generate a standard UUID (v4) string using the crypto module?
intermediate
- What is a Hash? Can a Hash be reversed back to the original text?
advanced
- What is the difference between encryption and hashing?