Node.js Crypto Module - Secure Hashing, HMAC Signatures & AES-256 Encryption

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.

1. One-Way Hashing with SHA-256

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

2. HMAC (Hash-based Message Authentication Code)

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);

3. Symmetric Encryption & Decryption with AES-256-GCM

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));

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. What is the difference between Hashing and Encryption?

Hashing (e.g. SHA-256) is a one-way mathematical function that turns data into a fixed-length string that cannot be decrypted back to the original text. Encryption (e.g. AES-256-GCM) is a two-way function that uses a secret key to scramble data into ciphertext, which can later be decrypted back into plain text with the correct key.

Q2. How do you generate a cryptographically secure random UUID in Node.js?

Use 'crypto.randomUUID()'. This generates a random Version 4 UUID (e.g. 'c9a646d3-9c61-4cd7-bf53-7c19639552b7') natively without requiring the third-party 'uuid' package.

Q3. Why should you use crypto.timingSafeEqual() when comparing secret tokens?

Standard JavaScript equality operators (===) terminate comparison on the first mismatched character, allowing attackers to measure execution time down to nanoseconds to guess passwords or secret signatures character-by-character (a Timing Attack). crypto.timingSafeEqual() executes in constant time regardless of where mismatches occur.

Explore Related Node.js Tutorials & Next Steps

Boost your server-side JavaScript proficiency by studying these closely connected core modules:

JWT Auth & Password Hashing

Implement production password hashing with bcrypt and crypto.

Security Best Practices

Defend against timing attacks and data leaks.

Buffers & Binary Data

Encode raw binary hashes into hex and base64.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!