'handle errors when decryption
i'm using aes-256-cfb algorithm to encrypt the data. encryption and decryption works fine. but if i add a invalid cipher text to decrypt function. it's return below like values.
"L1�"
in this scenario i return null from this function, i added try catch block. but it's not getting triggered.
const crypto = require('crypto');
const algorithm = 'aes-256-cfb';
function encryptText(keyStr, text) {
const hash = crypto.createHash('sha256');
hash.update(keyStr);
const keyBytes = hash.digest();
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv(algorithm, keyBytes, iv);
console.log('IV:', iv);
let enc = [iv, cipher.update(text, 'utf8')];
enc.push(cipher.final());
return Buffer.concat(enc).toString('base64');
}
function decryptText(keyStr, text) {
const hash = crypto.createHash('sha256');
hash.update(keyStr);
const keyBytes = hash.digest();
const contents = Buffer.from(text, 'base64');
const iv = contents.slice(0, 16);
const textBytes = contents.slice(16);
const decipher = crypto.createDecipheriv(algorithm, keyBytes, iv);
let res = decipher.update(textBytes, '', 'utf8');
res += decipher.final().toString();
return res;
}
const decrypted = decryptText(
'top_secret',
"BGWmMOjy+wcMtIPUtMwyoMOZFZ3"
);
console.log(decrypted)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
