const crypto = require('crypto');
// Password and salt (from the encryption process)
const password = 'mysecretpassword';
const salt = Buffer.from('0123456789abcdef0123456789abcdef', 'hex');
// Encrypted data and IV from the encryption process
const encryptedData = '7a9c2c7157819144ede3cb9532263cb97c94a7b45d95163bb79aa1af55d4101d';
const iv = Buffer.from('0123456789abcdef0123456789abcdef', 'hex');
// Generate a key from the password
function getKeyFromPassword(password, salt) {
// Use PBKDF2 to derive a key from the password
return crypto.pbkdf2Sync(password, salt, 100000, 32, 'sha256');
}
// Decrypt data
function decryptWithPassword(encryptedText, password, salt, iv) {
// Generate key from password
const key = getKeyFromPassword(password, salt);
// Create decipher
const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
// Decrypt
let decrypted = decipher.update(encryptedText, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
}
try {
// Decrypt using the password
const decrypted = decryptWithPassword(encryptedData, password, salt, iv);
console.log('Decrypted Text:', decrypted);
// Try with wrong password (should fail)
try {
const wrongPassword = 'wrongpassword';
const wrongDecrypted = decryptWithPassword(encryptedData, wrongPassword, salt, iv);
console.log('Should not reach here - wrong password worked!');
} catch (error) {
console.log('Wrong password failed (expected):', error.message);
}
} catch (error) {
console.error('Decryption failed:', error.message);
}