typescriptintermediate

Node.js Crypto Utility Functions

Common cryptographic operations: hashing, HMAC, encryption, random tokens, and password hashing.

typescript
import { createHash, createHmac, randomBytes, scrypt, timingSafeEqual } from 'node:crypto';
import { promisify } from 'node:util';

const scryptAsync = promisify(scrypt);

// SHA-256 hash
function sha256(data: string): string {
  return createHash('sha256').update(data).digest('hex');
}

// HMAC signature
function hmacSign(data: string, secret: string): string {
  return createHmac('sha256', secret).update(data).digest('hex');
}

// Verify HMAC (timing-safe)
function hmacVerify(data: string, secret: string, signature: string): boolean {
  const expected = hmacSign(data, secret);
  return timingSafeEqual(Buffer.from(expected), Buffer.from(signature));
}

// Generate random token
function generateToken(bytes = 32): string {
  return randomBytes(bytes).toString('hex');
}

// Generate URL-safe token
function generateUrlSafeToken(bytes = 32): string {
  return randomBytes(bytes).toString('base64url');
}

// Password hashing with scrypt
async function hashPassword(password: string): Promise<string> {
  const salt = randomBytes(16).toString('hex');
  const derived = (await scryptAsync(password, salt, 64)) as Buffer;
  return `${salt}:${derived.toString('hex')}`;
}

// Password verification
async function verifyPassword(password: string, hash: string): Promise<boolean> {
  const [salt, key] = hash.split(':');
  const derived = (await scryptAsync(password, salt, 64)) as Buffer;
  return timingSafeEqual(derived, Buffer.from(key, 'hex'));
}

// Usage
const hash = sha256('hello');
const token = generateToken();
const pwdHash = await hashPassword('mypassword');
const valid = await verifyPassword('mypassword', pwdHash);
console.log({ hash, token, pwdHash, valid });

Use Cases

  • Secure password storage and verification
  • API webhook signature validation
  • Generating secure session tokens

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.