Encrypting and decrypting data in Node.js can be achieved using various cryptographic libraries. One popular library is the crypto
module, which comes with Node.js. Below is a basic example demonstrating how to encrypt and decrypt data using the Advanced Encryption Standard (AES) algorithm with the crypto
module:
const crypto = require('crypto');
// Replace these keys with your own secret keys
const secretKey = 'mySecretKey123456';
const iv = 'myInitializationVector';
// Function to encrypt data
function encrypt(text) {
const cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(secretKey), Buffer.from(iv, 'hex'));
let encrypted = cipher.update(text, 'utf-8', 'hex');
encrypted += cipher.final('hex');
return encrypted;
}
// Function to decrypt data
function decrypt(encryptedText) {
const decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(secretKey), Buffer.from(iv, 'hex'));
let decrypted = decipher.update(encryptedText, 'hex', 'utf-8');
decrypted += decipher.final('utf-8');
return decrypted;
}
// Example usage
const originalText = 'Hello, this is a secret message!';
const encryptedText = encrypt(originalText);
const decryptedText = decrypt(encryptedText);
console.log('Original Text:', originalText);
console.log('Encrypted Text:', encryptedText);
console.log('Decrypted Text:', decryptedText);
In this example:
-
crypto.createCipheriv
is used to create a cipher with the AES-256-CBC algorithm. It takes the secret key and initialization vector (IV) as parameters. -
cipher.update
is called with the input text and encoding ('utf-8'), and thencipher.final
is called to obtain the final encrypted text. -
crypto.createDecipheriv
is used to create a decipher with the same algorithm, secret key, and IV. -
decipher.update
anddecipher.final
are used to obtain the decrypted text.
Remember to replace the secretKey
and iv
values with your own secure keys. Additionally, handle these keys securely, possibly using environment variables or a secure key management system. Also, note that security best practices may change over time, so it's important to stay updated on the latest recommendations.