Cryptography

suggest change

Node.js includes a comprehensive, built-in cryptography module (node:crypto) that wraps OpenSSL. It supports symmetric and asymmetric encryption, cryptographic hashing, HMACs, password derivation, digital signatures, and cryptographically secure random number generation. Modern Node.js also exposes the standard Web Cryptography API via globalThis.crypto.

Generating Secure Random Values

Never use Math.random() for security-critical tasks (tokens, session IDs, salts, nonces). Use crypto.randomBytes or crypto.randomUUID:

import crypto from 'node:crypto';

// Generate a random UUID (v4)
const uuid = crypto.randomUUID();
console.log('UUID:', uuid);

// Generate 32 cryptographically secure random bytes
const token = crypto.randomBytes(32).toString('hex');
console.log('Token:', token);

// Generate random integer in a specific range [min, max)
const randomPort = crypto.randomInt(1024, 65535);
console.log('Port:', randomPort);

Cryptographic Hashing and HMAC

SHA-256 Hashing

Hashing produces a fixed-length deterministic digest of input data:

import crypto from 'node:crypto';

function sha256(data) {
  return crypto.createHash('sha256').update(data, 'utf8').digest('hex');
}

console.log(sha256('Hello, World!'));
// dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986f

HMAC (Hash-Based Message Authentication Code)

HMAC combines a secret key with a hash function to authenticate data integrity:

import crypto from 'node:crypto';

function generateHmac(secretKey, message) {
  return crypto.createHmac('sha256', secretKey)
    .update(message)
    .digest('hex');
}

const secret = 'my-webhook-secret';
const payload = JSON.stringify({ event: 'order.created', id: 42 });
const signature = generateHmac(secret, payload);

Preventing Timing Attacks with timingSafeEqual

When verifying signatures or tokens, regular string equality (===) is vulnerable to timing attacks because it exits early on the first mismatched byte. Use crypto.timingSafeEqual:

function verifySignature(expectedSig, actualSig) {
  const expectedBuf = Buffer.from(expectedSig, 'hex');
  const actualBuf = Buffer.from(actualSig, 'hex');

  if (expectedBuf.length !== actualBuf.length) {
    return false;
  }

  return crypto.timingSafeEqual(expectedBuf, actualBuf);
}

Password Hashing with scrypt

Standard hashes (like MD5 or SHA-256) are too fast for password storage and vulnerable to GPU brute-force attacks. Use a slow, memory-hard derivation function like scrypt or pbkdf2:

import crypto from 'node:crypto';
import { promisify } from 'node:util';

const scryptAsync = promisify(crypto.scrypt);

async function hashPassword(password) {
  const salt = crypto.randomBytes(16).toString('hex');
  const derivedKey = await scryptAsync(password, salt, 64);
  return `${salt}:${derivedKey.toString('hex')}`;
}

async function verifyPassword(password, storedHash) {
  const [salt, key] = storedHash.split(':');
  const keyBuffer = Buffer.from(key, 'hex');
  const derivedKey = await scryptAsync(password, salt, 64);

  return crypto.timingSafeEqual(keyBuffer, derivedKey);
}

// Usage:
const hash = await hashPassword('correct-horse-battery-staple');
const isValid = await verifyPassword('correct-horse-battery-staple', hash); // true

Symmetric Encryption with AES-256-GCM

AES in Galois/Counter Mode (GCM) is an authenticated encryption standard that provides both confidentiality and data integrity verification:

import crypto from 'node:crypto';

const ALGORITHM = 'aes-256-gcm';
const IV_LENGTH = 12; // Recommended IV size for GCM is 12 bytes (96 bits)

function encrypt(text, key32Bytes) {
  const iv = crypto.randomBytes(IV_LENGTH);
  const cipher = crypto.createCipheriv(ALGORITHM, key32Bytes, iv);

  let encrypted = cipher.update(text, 'utf8', 'hex');
  encrypted += cipher.final('hex');

  const authTag = cipher.getAuthTag().toString('hex');

  // Pack IV, auth tag, and ciphertext together
  return `${iv.toString('hex')}:${authTag}:${encrypted}`;
}

function decrypt(encryptedPayload, key32Bytes) {
  const [ivHex, authTagHex, encryptedText] = encryptedPayload.split(':');

  const iv = Buffer.from(ivHex, 'hex');
  const authTag = Buffer.from(authTagHex, 'hex');
  const decipher = crypto.createDecipheriv(ALGORITHM, key32Bytes, iv);

  decipher.setAuthTag(authTag);

  let decrypted = decipher.update(encryptedText, 'hex', 'utf8');
  decrypted += decipher.final('utf8'); // Throws error if payload or tag is tampered

  return decrypted;
}

// Example usage:
const key = crypto.randomBytes(32); // 256-bit secret key
const ciphertext = encrypt('Sensitive database record', key);
const plaintext = decrypt(ciphertext, key);
console.log(plaintext); // "Sensitive database record"

Digital Signatures with Public-Key Cryptography (Ed25519)

Ed25519 produces compact keys and signatures with state-of-the-art security and performance:

import crypto from 'node:crypto';

// 1. Generate key pair
const { publicKey, privateKey } = crypto.generateKeyPairSync('ed25519');

// 2. Sign message with private key
const message = Buffer.from('Authorize transaction #1234');
const signature = crypto.sign(null, message, privateKey);

// 3. Verify signature with public key
const isVerified = crypto.verify(null, message, publicKey, signature);
console.log('Signature valid:', isVerified); // true

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents