Skip to main content
Practice Problems

How to use the Crypto module in Node.js for hashing and encryption?

The Crypto Module

The built-in crypto module provides cryptographic functionality for hashing, encryption, decryption, and generating random values. It's essential for security-sensitive operations.


Hashing (One-way)

Hashing converts data into a fixed-size string. It's irreversible — you cannot get the original data back.

js
const crypto = require('crypto'); // Simple hash const hash = crypto.createHash('sha256') .update('Hello World') .digest('hex'); console.log(hash); // a591a6d40bf420404a011733cfb7b190d62c65bf0bcda32b57b277d9ad9f146e

Common Hash Algorithms

AlgorithmOutput SizeUse Case
md5128-bitChecksums (NOT for passwords)
sha256256-bitData integrity, signatures
sha512512-bitHigher security needs

Password Hashing with Salt

js
function hashPassword(password) { const salt = crypto.randomBytes(16).toString('hex'); const hash = crypto.pbkdf2Sync(password, salt, 100000, 64, 'sha512').toString('hex'); return { salt, hash }; } function verifyPassword(password, salt, hash) { const verify = crypto.pbkdf2Sync(password, salt, 100000, 64, 'sha512').toString('hex'); return verify === hash; } const { salt, hash } = hashPassword('myPassword123'); console.log(verifyPassword('myPassword123', salt, hash)); // true console.log(verifyPassword('wrongPassword', salt, hash)); // false

Symmetric Encryption (AES)

Same key for encryption and decryption:

js
const algorithm = 'aes-256-cbc'; const key = crypto.randomBytes(32); const iv = crypto.randomBytes(16); function encrypt(text) { const cipher = crypto.createCipheriv(algorithm, key, iv); let encrypted = cipher.update(text, 'utf8', 'hex'); encrypted += cipher.final('hex'); return { iv: iv.toString('hex'), encrypted }; } function decrypt(encrypted, ivHex) { const decipher = crypto.createDecipheriv( algorithm, key, Buffer.from(ivHex, 'hex') ); let decrypted = decipher.update(encrypted, 'hex', 'utf8'); decrypted += decipher.final('utf8'); return decrypted; } const { iv: ivHex, encrypted } = encrypt('Secret message'); console.log('Encrypted:', encrypted); console.log('Decrypted:', decrypt(encrypted, ivHex));

HMAC (Hash-based Message Authentication Code)

Verifies both data integrity and authenticity:

js
const secret = 'my-secret-key'; const hmac = crypto.createHmac('sha256', secret) .update('data to verify') .digest('hex'); // Verify function verifyHmac(data, receivedHmac, secret) { const expected = crypto.createHmac('sha256', secret) .update(data) .digest('hex'); return crypto.timingSafeEqual( Buffer.from(receivedHmac), Buffer.from(expected) ); }

Generating Random Values

js
// Random bytes (for tokens, keys, salts) const token = crypto.randomBytes(32).toString('hex'); // Random UUID const uuid = crypto.randomUUID(); // Random integer in range const randomInt = crypto.randomInt(1, 100);

Quick Reference

OperationMethodUse Case
HashcreateHash()Checksums, data fingerprints
Password hashpbkdf2 / scryptPassword storage
Encrypt/DecryptcreateCipheriv()Sensitive data at rest
HMACcreateHmac()API signatures, webhooks
Random bytesrandomBytes()Tokens, salts, keys
UUIDrandomUUID()Unique identifiers

Important: Never use md5 or sha1 for passwords. Use pbkdf2, scrypt, or bcrypt with proper salt and iteration count. Always use timingSafeEqual() for comparing hashes to prevent timing attacks.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.

Finished reading?
Practice Problems