The crypto module provides cryptographic functionality including hashing, encryption, and secure random generation. Here's how to use it.
Hashing#
HMAC (Hash-based Message Authentication)#
Password Hashing#
Random Bytes#
UUID Generation#
Symmetric Encryption (AES)#
Asymmetric Encryption (RSA)#
Digital Signatures#
Key Derivation#
Secure Token Generation#
File Hashing#
Best Practices#
Hashing:
✓ Use SHA-256 or SHA-512
✓ Use bcrypt/scrypt for passwords
✓ Always use salt
✓ Use timingSafeEqual for comparison
Encryption:
✓ Use AES-256-GCM for symmetric
✓ Use RSA-OAEP for asymmetric
✓ Generate random IVs
✓ Store keys securely
Random:
✓ Use crypto.randomBytes
✓ Use crypto.randomUUID for UUIDs
✓ Use crypto.randomInt for numbers
✓ Never use Math.random for security
Avoid:
✗ MD5 or SHA-1 for security
✗ Hardcoded keys/secrets
✗ ECB mode encryption
✗ Custom crypto implementations
Conclusion#
The Node.js crypto module provides comprehensive cryptographic functionality. Use modern algorithms like SHA-256 for hashing, AES-256-GCM for encryption, and scrypt for password hashing. Always use cryptographically secure random number generation and never roll your own crypto. Store keys securely and use appropriate key lengths for your security requirements.