Security is non-negotiable in modern web applications. The built-in crypto module encapsulates OpenSSL's cryptographic functions, providing high-performance cryptographic primitives for hashing, message authentication (HMAC), symmetric encryption (AES), and random token generation.
Hashing generates a unique digital fingerprint of arbitrary data. If even a single punctuation mark changes in the input, the output hash changes completely:
const crypto = require('crypto');
function generateHash(data) {
return crypto
.createHash('sha256')
.update(data)
.digest('hex'); // 'hex', 'base64', or raw Buffer
}
console.log('SHA-256 Hash:', generateHash('student_password_2026'));
// Output: 4434db0349603e8ff9a7008cfbf6d87042a9b2b522ea946d45e527d825c34cb2
An HMAC uses a secret cryptographic key alongside a hashing algorithm to verify both data integrity and authenticity. This is the foundation of JSON Web Tokens (JWT):
function generateHMAC(payload, secretKey) {
return crypto
.createHmac('sha256', secretKey)
.update(payload)
.digest('hex');
}
const secret = 'super-secret-company-key';
const signature = generateHMAC('user_id=105&role=admin', secret);
console.log('HMAC Signature:', signature);
AES-256-GCM (Galois/Counter Mode) is the industry standard for authenticated two-way encryption:
// Secure 32-byte (256-bit) encryption key
const KEY = crypto.randomBytes(32);
function encryptText(plainText) {
const iv = crypto.randomBytes(16); // Initialization Vector
const cipher = crypto.createCipheriv('aes-256-gcm', KEY, iv);
let encrypted = cipher.update(plainText, 'utf8', 'hex');
encrypted += cipher.final('hex');
const authTag = cipher.getAuthTag().toString('hex');
return {
iv: iv.toString('hex'),
encryptedData: encrypted,
authTag: authTag
};
}
function decryptText(cipherObj) {
const decipher = crypto.createDecipheriv(
'aes-256-gcm',
KEY,
Buffer.from(cipherObj.iv, 'hex')
);
decipher.setAuthTag(Buffer.from(cipherObj.authTag, 'hex'));
let decrypted = decipher.update(cipherObj.encryptedData, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
}
const secretSecret = encryptText('Confidential Student Grades: 98%');
console.log('Encrypted Payload:', secretSecret);
console.log('Decrypted Text:', decryptText(secretSecret));
Boost your server-side JavaScript proficiency by studying these closely connected core modules:
Implement production password hashing with bcrypt and crypto.
Defend against timing attacks and data leaks.
Encode raw binary hashes into hex and base64.