const crypto = require('crypto');
// Helper function to demonstrate error handling
function demonstrateError(scenario) {
console.log(`\n=== ${scenario} ===`);
try {
switch (scenario) {
case 'INVALID_KEY_LENGTH':
// Key is too short for AES-256 (needs 32 bytes)
const shortKey = Buffer.from('tooshort', 'utf8');
const iv = crypto.randomBytes(16);
crypto.createDecipheriv('aes-256-cbc', shortKey, iv);
break;
case 'INVALID_IV_LENGTH':
// IV is too short for AES-CBC (needs 16 bytes)
const key = crypto.randomBytes(32);
const shortIv = Buffer.from('tooshort', 'utf8');
crypto.createDecipheriv('aes-256-cbc', key, shortIv);
break;
case 'INVALID_AUTH_TAG':
// Using GCM without setting auth tag
const gcmKey = crypto.randomBytes(32);
const gcmIv = crypto.randomBytes(12);
const gcmDecipher = crypto.createDecipheriv('aes-256-gcm', gcmKey, gcmIv);
gcmDecipher.setAAD(Buffer.from('some data'));
// Forgot to call setAuthTag()
gcmDecipher.update('somedata', 'hex', 'utf8');
gcmDecipher.final('utf8');
break;
case 'INVALID_CIPHERTEXT':
// Corrupted ciphertext
const cipher = crypto.createCipheriv('aes-256-cbc', crypto.randomBytes(32), crypto.randomBytes(16));
const encrypted = cipher.update('test', 'utf8', 'hex') + cipher.final('hex');
// Corrupt the ciphertext
const corrupted = encrypted.substring(0, 10) + '00' + encrypted.substring(12);
const decipher = crypto.createDecipheriv('aes-256-cbc', crypto.randomBytes(32), crypto.randomBytes(16));
decipher.update(corrupted, 'hex', 'utf8');
decipher.final('utf8');
break;
}
} catch (error) {
console.log(`Error: ${error.code} - ${error.message}`);
}
}
// Demonstrate different error scenarios
demonstrateError('INVALID_KEY_LENGTH');
demonstrateError('INVALID_IV_LENGTH');
demonstrateError('INVALID_AUTH_TAG');
demonstrateError('INVALID_CIPHERTEXT');