typescriptintermediate
Crypto Hashing and HMAC
Generate secure hashes, HMACs, and checksums using Node.js built-in crypto module.
typescriptPress ⌘/Ctrl + Shift + C to copy
import { createHash, createHmac, randomBytes, timingSafeEqual } from 'crypto';
import { createReadStream } from 'fs';
// Hash a string
function hash(data: string, algorithm = 'sha256'): string {
return createHash(algorithm).update(data).digest('hex');
}
console.log('SHA-256:', hash('hello'));
console.log('SHA-512:', hash('hello', 'sha512'));
console.log('MD5:', hash('hello', 'md5'));
// HMAC (keyed hash)
function hmac(data: string, secret: string, algorithm = 'sha256'): string {
return createHmac(algorithm, secret).update(data).digest('hex');
}
const secret = 'my-secret-key';
console.log('\nHMAC:', hmac('message', secret));
// Verify HMAC (timing-safe)
function verifyHmac(data: string, expectedHmac: string, secret: string): boolean {
const computed = hmac(data, secret);
const a = Buffer.from(computed, 'hex');
const b = Buffer.from(expectedHmac, 'hex');
if (a.length !== b.length) return false;
return timingSafeEqual(a, b);
}
const sig = hmac('payload', secret);
console.log('Verify valid:', verifyHmac('payload', sig, secret));
console.log('Verify invalid:', verifyHmac('tampered', sig, secret));
// File checksum (streaming)
async function fileChecksum(path: string, algorithm = 'sha256'): Promise<string> {
return new Promise((resolve, reject) => {
const hash = createHash(algorithm);
const stream = createReadStream(path);
stream.on('data', (chunk) => hash.update(chunk));
stream.on('end', () => resolve(hash.digest('hex')));
stream.on('error', reject);
});
}
// Content-based cache key
function cacheKey(content: string): string {
return hash(content).substring(0, 12);
}
console.log('\nCache key:', cacheKey('body { color: red }'));
// Generate random token
function generateToken(bytes = 32): string {
return randomBytes(bytes).toString('hex');
}
console.log('Token:', generateToken());
console.log('Short token:', generateToken(8));
// Webhook signature verification (GitHub-style)
function verifyWebhookSignature(
payload: string,
signature: string,
secret: string
): boolean {
const expected = 'sha256=' + hmac(payload, secret);
const a = Buffer.from(expected);
const b = Buffer.from(signature);
if (a.length !== b.length) return false;
return timingSafeEqual(a, b);
}
const payload = JSON.stringify({ event: 'push' });
const webhookSig = 'sha256=' + hmac(payload, 'webhook-secret');
console.log('\nWebhook valid:', verifyWebhookSignature(payload, webhookSig, 'webhook-secret'));Use Cases
- Webhook signature verification
- File integrity checking
- API authentication with HMAC
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptintermediate
Node.js Crypto Utility Functions
Common cryptographic operations: hashing, HMAC, encryption, random tokens, and password hashing.
Best for: Secure password storage and verification
#nodejs#crypto
typescriptbeginner
UUID and Nano ID Generator
Generate RFC-4122 v4 UUIDs and URL-safe nano IDs using the Node.js built-in crypto module with zero deps.
Best for: Database primary keys
#uuid#crypto
typescriptbeginner
Bcrypt Password Hash & Verify
Hash and verify passwords with bcrypt using configurable salt rounds and timing-safe comparison.
Best for: User registration
#bcrypt#password
typescriptadvanced
Node.js Worker Threads for Parallel Processing
Use Worker Threads to run CPU-intensive tasks in parallel without blocking the event loop.
Best for: CPU-intensive data processing without blocking
#nodejs#worker-threads