The node:crypto module provides robust cryptographic functionality including message digest hashing (SHA-256), Hash-based Message Authentication Codes (HMAC), symmetric encryption (AES-256-GCM), asymmetric RSA keys, and cryptographically secure random number generation.
flowchart TD
A["Plaintext Data"] --> B["Cipher (AES-256-GCM + Secret Key + IV)"]
B --> C["Encrypted Ciphertext + Auth Tag"]
C --> D["Decipher (AES-256-GCM + Secret Key + IV + Auth Tag)"]
D --> E["Original Plaintext Data"]
import crypto from 'node:crypto';
// 1. Password Hashing via SHA-256
function hashPassword(password) {
return crypto.createHash('sha256').update(password).digest('hex');
}
console.log('Hashed Password:', hashPassword('SecretPass123!'));
// 2. Symmetric AES-256-GCM Encryption & Decryption
const ALGORITHM = 'aes-256-gcm';
const SECRET_KEY = crypto.randomBytes(32); // 256 bits key
const IV = crypto.randomBytes(16); // 128 bits initialization vector
function encryptData(text) {
const cipher = crypto.createCipheriv(ALGORITHM, SECRET_KEY, IV);
let encrypted = cipher.update(text, 'utf8', 'hex');
encrypted += cipher.final('hex');
const authTag = cipher.getAuthTag().toString('hex');
return { encrypted, iv: IV.toString('hex'), authTag };
}
function decryptData(encrypted, ivHex, authTagHex) {
const decipher = crypto.createDecipheriv(ALGORITHM, SECRET_KEY, Buffer.from(ivHex, 'hex'));
decipher.setAuthTag(Buffer.from(authTagHex, 'hex'));
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
}
const payload = "Confidential API Secret Token";
const { encrypted, iv, authTag } = encryptData(payload);
console.log('Encrypted Payload:', encrypted);
const original = decryptData(encrypted, iv, authTag);
console.log('Decrypted Output:', original);
scrypt or pbkdf2 for Passwords: Do not use raw SHA-256 or MD5 for password storage; use crypto.scrypt() or bcrypt with salt to protect against rainbow table attacks.authTag during deciphering to prevent ciphertext tampering attacks.crypto.randomBytes(): Never use Math.random() for security token or cryptographic key generation; always use crypto.randomBytes() or crypto.randomUUID().Generate a secure Version 4 UUID string using the modern crypto.randomUUID() method in Node.js.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
You've completed this section! Take a quick 5-question quiz to check your understanding.