Node.js Crypto Module
The Node.js crypto module provides cryptographic functionality via wrappers around OpenSSL ÔÇö hashing, HMAC, ciphers, deciphers, signing, and verification. Use it for secure data handling in your apps.
Node.js Tutorial:-
Complete Python Course:-
What is Hash?
A hash is a fixed-length string of bits generated deterministically from any input. Same input always produces the same hash; tiny changes produce completely different hashes. Used for integrity checks and password storage (with salt).
What is HMAC?
HMAC (Hash-based Message Authentication Code) combines a hash function with a secret key ÔÇö providing both data integrity AND authenticity. Without the key, the HMAC cannot be recreated.
Example 1: HMAC with SHA-256
// crypto_example1.js
const crypto = require('crypto');
const secret = 'abcdefg';
const hash = crypto.createHmac('sha256', secret)
.update('Welcome to UpdateGadh')
.digest('hex');
console.log(hash);
Example 2: Modern AES Encryption
Note: createCipher is deprecated. Use createCipheriv with a key and IV:
const crypto = require('crypto');
const algorithm = 'aes-192-cbc';
const password = 'a password';
const key = crypto.scryptSync(password, 'salt', 24);
const iv = Buffer.alloc(16, 0);
const cipher = crypto.createCipheriv(algorithm, key, iv);
let encrypted = cipher.update('Hello UpdateGadh', 'utf8', 'hex');
encrypted += cipher.final('hex');
console.log(encrypted);
Example 3: Decryption
const decipher = crypto.createDecipheriv(algorithm, key, iv);
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
console.log(decrypted);
Common Use Cases
- Password hashing (use
scryptorbcryptfor passwords, not plain SHA). - API token signing with HMAC.
- Encrypting sensitive data at rest.
- Generating secure random tokens via
crypto.randomBytes.
Download New Real Time Projects:- Click here
Complete Advance AI topics:-
Conclusion
The crypto module gives Node.js production-grade security tools. Prefer the modern IV-based APIs and dedicated password hashing functions for real apps. For more guides, stay tuned to .
npm crypto
crypto-js
node js crypto example
node:crypto randombytes
node crypto createhash
crypto-js download
crypto hash nodejs
node js crypto tutorial