Node.js provides powerful cryptographic functionalities through its built-in crypto module. This guide explores various encryption algorithms and hashing techniques, complete with practical JavaScript implementations.
Understanding the Crypto Module
The crypto module offers common cryptographic functions including hash computations, HMAC generation, encryption/decryption, and digital signatures. While JavaScript implementations of these algorithms exist, Node.js leverages C/C++ implementations for significantly better performance.
Core Features:
- Hash generation (MD5, SHA1, SHA256, etc.)
- HMAC creation
- Symmetric encryption (AES)
- Asymmetric encryption (RSA)
- Key exchange protocols (Diffie-Hellman)
Common Hashing Algorithms
MD5 Hashing Example
import crypto from 'node:crypto';
const hash = crypto.createHash('md5');
hash.update('Hello, world!');
hash.update('Hello, nodejs!');
console.log(hash.digest('hex'));
// Output: 7e1977739c748beac0c0fd14fd26a544SHA Variants
Simply replace 'md5' with:
'sha1'for SHA-1'sha256'for SHA-256'sha512'for SHA-512
HMAC: Keyed-Hash Message Authentication
HMAC provides a way to verify both data integrity and authenticity using a shared secret key.
import crypto from 'node:crypto';
const hmac = crypto.createHmac('sha256', 'secret-key');
hmac.update('Hello, world!');
hmac.update('Hello, nodejs!');
console.log(hmac.digest('hex'));
// Output: 80f7e22570...Symmetric Encryption with AES
AES (Advanced Encryption Standard) is a widely used symmetric encryption algorithm where the same key is used for both encryption and decryption.
👉 Learn more about advanced encryption techniques
Implementation Example:
import crypto from 'node:crypto';
function aesEncrypt(key, iv, msg) {
const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
let encrypted = cipher.update(msg, 'utf8', 'hex');
encrypted += cipher.final('hex');
return encrypted;
}
function aesDecrypt(key, iv, encrypted) {
const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
}
// Example usage:
const key = '32bytePassw0rdPassw0rdPassw0rd';
const iv = '16byteInitialVect';
const msg = 'Secret message';
const encrypted = aesEncrypt(key, iv, msg);
const decrypted = aesDecrypt(key, iv, encrypted);
console.log(`Encrypted: ${encrypted}`);
console.log(`Decrypted: ${decrypted}`);Diffie-Hellman Key Exchange
This protocol allows two parties to establish a shared secret over an insecure channel.
import crypto from 'node:crypto';
// First party setup
const alice = crypto.createDiffieHellman(512);
const aliceKeys = alice.generateKeys();
// Second party setup
const prime = alice.getPrime();
const generator = alice.getGenerator();
const bob = crypto.createDiffieHellman(prime, generator);
const bobKeys = bob.generateKeys();
// Secret computation
const aliceSecret = alice.computeSecret(bobKeys);
const bobSecret = bob.computeSecret(aliceKeys);
console.log('Alice secret:', aliceSecret.toString('hex'));
console.log('Bob secret:', bobSecret.toString('hex'));RSA Asymmetric Encryption
RSA uses separate keys for encryption and decryption, making it ideal for secure communications.
👉 Explore blockchain security applications
Generating RSA Keys
openssl genrsa -aes256 -out rsa-key.pem 2048
openssl rsa -in rsa-key.pem -outform PEM -out rsa-prv.pem
openssl rsa -in rsa-key.pem -outform PEM -pubout -out rsa-pub.pemRSA Implementation
import fs from 'node:fs';
import crypto from 'node:crypto';
function loadKey(file) {
return fs.readFileSync(file, 'utf8');
}
const prvKey = loadKey('./rsa-prv.pem');
const pubKey = loadKey('./rsa-pub.pem');
const message = 'Confidential data';
// Public key encryption
const encrypted = crypto.publicEncrypt(pubKey, Buffer.from(message));
console.log('Encrypted:', encrypted.toString('hex'));
// Private key decryption
const decrypted = crypto.privateDecrypt(prvKey, encrypted);
console.log('Decrypted:', decrypted.toString());FAQ Section
Q: When should I use symmetric vs. asymmetric encryption?
A: Use symmetric encryption (AES) for bulk data encryption and asymmetric encryption (RSA) for key exchange or small data encryption.
Q: How secure is SHA-1 compared to SHA-256?
A: SHA-1 is considered broken for security purposes. Always prefer SHA-256 or stronger variants for cryptographic applications.
Q: Can I use the same IV for multiple AES encryptions?
A: No, using the same IV with the same key compromises security. Always generate a unique IV for each encryption operation.
Q: How long should my RSA keys be?
A: For modern security, use at least 2048-bit keys. Consider 4096-bit for long-term security needs.
Q: What's the difference between HMAC and regular hashing?
A: HMAC includes a secret key, providing both integrity verification and authenticity assurance, whereas regular hashes only verify integrity.
Best Practices for Cryptographic Operations
- Always use cryptographically secure random number generators for key/IV generation
- Prefer authenticated encryption modes like AES-GCM when possible
- Regularly rotate encryption keys
- Store keys securely using environment variables or dedicated key management systems
- Keep your cryptographic libraries up-to-date
Remember that proper implementation is just as important as choosing strong algorithms. When in doubt, consult with security professionals or use well-audited libraries.