const crypto = require('crypto');
// Function to derive a key from a password
function getKeyFromPassword(password, salt) {
return crypto.pbkdf2Sync(password, salt, 100000, 32, 'sha256');
}
// Encryption function using a password
function encryptWithPassword(text, password) {
// Generate a random salt
const salt = crypto.randomBytes(16);
// Derive key from password
const key = getKeyFromPassword(password, salt);
// Generate a random IV
const iv = crypto.randomBytes(16);
// Create cipher
const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
// Encrypt the data
let encrypted = cipher.update(text, 'utf8', 'hex');
encrypted += cipher.final('hex');
// Return the salt, IV, and encrypted data
return {
salt: salt.toString('hex'),
iv: iv.toString('hex'),
encryptedData: encrypted
};
}
// Decryption function using a password
function decryptWithPassword(encryptedData, password, salt, iv) {
// Convert hex strings back to buffers
const saltBuffer = Buffer.from(salt, 'hex');
const ivBuffer = Buffer.from(iv, 'hex');
// Derive the same key from the password and salt
const key = getKeyFromPassword(password, saltBuffer);
// Create decipher
const decipher = crypto.createDecipheriv('aes-256-cbc', key, ivBuffer);
// Decrypt the data
let decrypted = decipher.update(encryptedData, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
}
// Example usage
const password = 'my-secret-password';
const message = 'This is a secret message encrypted with a password';
// Encrypt the message
const encrypted = encryptWithPassword(message, password);
console.log('Encrypted:', encrypted);
// Decrypt the message
const decrypted = decryptWithPassword(
encrypted.encryptedData,
password,
encrypted.salt,
encrypted.iv
);
console.log('Decrypted:', decrypted);
console.log('Decryption successful:', message === decrypted);