const crypto = require('crypto');
// The message to encrypt
const message = 'This is a secret message that needs to be encrypted';
// Generate encryption key and IV
const key = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);
// Encryption function using Cipher
function encrypt(text) {
// Create cipher
const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
// Encrypt data
let encrypted = cipher.update(text, 'utf8', 'hex');
encrypted += cipher.final('hex');
return encrypted;
}
// Decryption function using Decipher
function decrypt(encryptedText) {
// Create decipher with the same key and IV
const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
// Decrypt data
let decrypted = decipher.update(encryptedText, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
}
// Encrypt the message
const encryptedMessage = encrypt(message);
console.log('Original Message:', message);
console.log('Encrypted Message:', encryptedMessage);
// Decrypt the message
const decryptedMessage = decrypt(encryptedMessage);
console.log('Decrypted Message:', decryptedMessage);
// Verify the result
console.log('Decryption successful:', message === decryptedMessage);