I am trying to encrypt/decrypt. Encryption works fine and it writes encrypted data to file. While decrypting I am getting an error of length issue. I have used "utf-8" format but error continues.
/ A decrypt function
function decrypt(file) {
let data = JSON.parse(fs.readFileSync(file));
let iv = Buffer.from(data.iv, 'hex');
let encryptedText =
Buffer.from(data.encryptedData, 'hex');
// Creating Decipher
let decipher = crypto.createDecipheriv(
algorithm, Buffer.from(key), iv);
// Updating encrypted text
let decrypted = decipher.update(encryptedText);
let decrypted = Buffer.concat([decrypted, decipher.final()]);
// // returns data after decryption
return decrypted.toString();
}
//run
// Decrypts output
console.log(decrypt('./file.json.enc'));
Error: error:0606506D:digital envelope routines:EVP_DecryptFinal_ex:wrong final block length
at Decipheriv.final (internal/crypto/cipher.js:170:29)
at decrypt (/Users/chandrasekarareddy/Documents/projects/encrypt/final.js:48:22)
at Object.<anonymous> (/Users/chandrasekarareddy/Documents/projects/encrypt/final.js:64:13)
at Module._compile (internal/modules/cjs/loader.js:959:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
at Module.load (internal/modules/cjs/loader.js:815:32)
at Function.Module._load (internal/modules/cjs/loader.js:727:14)
at Function.Module.runMain (internal/modules/cjs/loader.js:1047:10)
at internal/main/run_main_module.js:17:11 {
library: 'digital envelope routines',
function: 'EVP_DecryptFinal_ex',
reason: 'wrong final block length',
code: 'ERR_OSSL_EVP_WRONG_FINAL_BLOCK_LENGTH'
}
Its throwing error at decipher.final(). Instead of file as input param if I pass text it's wrong fine. Thanks in advance