The built-in `crypto` module in Node.js provides a set of cryptographic functionalities, including tools for hashing, encryption, and decryption. This guide covers two of the most common use cases.
Hashing with SHA256
Hashing is a one-way process that converts an input into a fixed-size string of bytes. It's commonly used for verifying data integrity and storing passwords securely (always with a salt!).
const crypto = require('crypto');
const secret = 'my-secret-message';
const hash = crypto.createHash('sha256')
.update(secret)
.digest('hex');
console.log(hash);
// Outputs a 64-character hexadecimal string
Symmetric Encryption with AES
Encryption is a two-way process. AES (Advanced Encryption Standard) is a widely used symmetric encryption algorithm. You need a secret key and an initialization vector (IV) for both encryption and decryption.
const crypto = require('crypto');
const algorithm = 'aes-256-cbc';
const key = crypto.randomBytes(32); // 256-bit key
const iv = crypto.randomBytes(16); // 128-bit IV
function encrypt(text) {
let cipher = crypto.createCipheriv(algorithm, Buffer.from(key), iv);
let encrypted = cipher.update(text);
encrypted = Buffer.concat([encrypted, cipher.final()]);
return { iv: iv.toString('hex'), encryptedData: encrypted.toString('hex') };
}
function decrypt(data) {
let iv = Buffer.from(data.iv, 'hex');
let encryptedText = Buffer.from(data.encryptedData, 'hex');
let decipher = crypto.createDecipheriv(algorithm, Buffer.from(key), iv);
let decrypted = decipher.update(encryptedText);
decrypted = Buffer.concat([decrypted, decipher.final()]);
return decrypted.toString();
}
const hw = encrypt("Hello World");
console.log(hw);
console.log(decrypt(hw));
Comments
Post a Comment