Script Valley
Node.js: The Complete Runtime
Node.js Core ModulesLesson 3.5

Node.js crypto module: hashing, encryption, and random values

crypto.createHash, SHA-256, MD5, crypto.randomBytes, crypto.randomUUID, crypto.createHmac, timing-safe comparison, password hashing with scrypt

Never Roll Your Own Crypto — Use the Built-in Module

The built-in crypto module wraps OpenSSL. Use it for hashing, HMAC signatures, and generating secure random values.

const crypto = require('crypto');

const hash = crypto
  .createHash('sha256')
  .update('my-data')
  .digest('hex');

const sig = crypto
  .createHmac('sha256', process.env.SECRET)
  .update(JSON.stringify(payload))
  .digest('hex');

const token = crypto.randomBytes(32).toString('hex');
const uuid = crypto.randomUUID();

Password Hashing with scrypt

const { scrypt, randomBytes, timingSafeEqual } = crypto;
const { promisify } = require('util');
const scryptAsync = promisify(scrypt);

async function hashPassword(password) {
  const salt = randomBytes(16).toString('hex');
  const buf = await scryptAsync(password, salt, 64);
  return buf.toString('hex') + '.' + salt;
}

async function verifyPassword(stored, input) {
  const [hash, salt] = stored.split('.');
  const buf = await scryptAsync(input, salt, 64);
  return timingSafeEqual(Buffer.from(hash, 'hex'), buf);
}

Never compare password hashes with ===. Use timingSafeEqual to prevent timing attacks.