The crypto module provides cryptographic functionality for hashing, encryption, and secure random numbers.
Hashing#
Password Hashing#
Symmetric Encryption#
HMAC#
Random Values#
Key Derivation#
Digital Signatures#
Practical Examples#
Best Practices#
Algorithms:
✓ Use scrypt or Argon2 for passwords
✓ Use AES-256-GCM for encryption
✓ Use SHA-256 or SHA-512 for hashing
✓ Use HMAC for message authentication
Security:
✓ Use crypto.randomBytes for tokens
✓ Use timing-safe comparison
✓ Generate unique IVs/salts
✓ Store salts with hashes
Key Management:
✓ Use environment variables
✓ Rotate keys periodically
✓ Use key derivation functions
✓ Never hardcode secrets
Avoid:
✗ MD5 or SHA1 for security
✗ ECB mode for encryption
✗ Predictable IVs or salts
✗ Rolling your own crypto
Conclusion#
The Node.js crypto module provides comprehensive cryptographic functionality. Use scrypt for password hashing, AES-GCM for encryption, and HMAC for authentication. Always use secure random generation for tokens and keys. Follow best practices for algorithm selection and key management.