Beginner LevelNode JS
How do you generate cryptographic hashes and random tokens using node:crypto?
❓ Interview Prompt: Explain `node:crypto` module, `crypto.createHash()`, `crypto.createHmac()`, and `crypto.randomBytes()` for secure token generation.
The native 'node:crypto' module provides cryptographic functionality:
•
'crypto.createHash('sha256')': Computes one-way cryptographic message digests.
•
'crypto.createHmac('sha256', secret)': Computes secret-key HMAC signatures.
•
'crypto.randomBytes(32)': Generates cryptographically strong pseudo-random bytes.
Code Implementation Example
javascript
import crypto from 'node:crypto';
// Generate secure 32-byte hex token
const resetToken = crypto.randomBytes(32).toString('hex');
// Compute SHA-256 hash of a string
const hash = crypto.createHash('sha256').update('secretData').digest('hex');
console.log('Random Token:', resetToken);
console.log('SHA-256 Hash:', hash);💡Generating secure random tokens and computing SHA-256 hashes.
🎯 Interview Key Takeaway
Use node:crypto randomBytes for security tokens instead of Math.random().
#crypto#hash#SHA-256#randomBytes#Beginner
Back to all Node JS Questions→