typescriptintermediate
Node.js Crypto Utility Functions
Common cryptographic operations: hashing, HMAC, encryption, random tokens, and password hashing.
typescriptPress ⌘/Ctrl + Shift + C to copy
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.
typescriptintermediate
Crypto Hashing and HMAC
Generate secure hashes, HMACs, and checksums using Node.js built-in crypto module.
Best for: Webhook signature verification
#nodejs#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
typescriptintermediate
Node.js Token Bucket Rate Limiter
Implement an in-memory token bucket rate limiter for controlling API request throughput.
Best for: Protecting APIs from abuse and DDoS
#nodejs#rate-limiting
typescriptbeginner
CORS Configuration Middleware
Configure Cross-Origin Resource Sharing with origin allowlists, credentials, and preflight handling.
Best for: API CORS configuration
#nodejs#cors