Node.js – Crypto Module
Subject: nodejs
Node.js – Crypto Module
The crypto
module in Node.js provides cryptographic functionality including hashing, encryption, decryption, HMAC, and key pair generation. It uses OpenSSL under the hood and is built into Node.js (no installation required).
Why Use the crypto Module?
- Data security: Secure sensitive data like passwords.
- Authentication: Validate message integrity using HMACs.
- Encryption: Protect data using symmetric or asymmetric encryption.
- Token Generation: Generate secure random tokens for authentication.
Importing the Crypto Module
1. Creating a Hash
Hashing is a one-way operation used for securely storing data like passwords.
Example Output:
2. Generating HMAC
Create a keyed hash (used for authentication and message integrity).
3. Generating Random Bytes
Generate cryptographically secure random values (e.g., for tokens).
4. Symmetric Encryption and Decryption (AES)
5. Public/Private Key Generation and Signing
Real-World Use Cases
- Secure password storage (e.g., bcrypt uses hashing internally)
- API authentication with HMACs
- JWT signing and verification
- Token generation for password resets or session flows
- File encryption and decryption
Key Takeaways
- The
crypto
module allows secure operations in Node.js using built-in cryptographic functions. - Use it for hashing, encryption, key generation, and random value creation.
- Always choose strong algorithms like SHA-256, AES-256, and RSA.
- Do not implement your own cryptographic logic—use tested methods from the module.