I am trying to decrypt a PDF file using node js,PDF file encrypted by third party using C# .
I am having a hard time because I keep getting this error:
D:\IMP\DevOps Implementation\New folder (2)> node index1.js
internal/crypto/cipher.js:172
const ret = this[kHandle].final();
^
Error: error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt
at Decipheriv.final (internal/crypto/cipher.js:172:29)
at Object.AESCrypt.decrypt (D:\IMP\DevOps Implementation\New folder (2)\index1.js:12:18)
at D:\IMP\DevOps Implementation\New folder (2)\index1.js:57:24
at FSReqCallback.readFileAfterClose [as oncomplete] (internal/fs/read_file_context.js:63:3) {
library: 'digital envelope routines',
function: 'EVP_DecryptFinal_ex',
reason: 'bad decrypt',
code: 'ERR_OSSL_EVP_BAD_DECRYPT'
}
we are using below code for encryption(C#)
private void FileEncrypt(string inputFile, string outputfile, string password)
{
byte[] salt = GenerateSalt();
byte[] passwords = Encoding.UTF8.GetBytes(password);
RijndaelManaged AES = new RijndaelManaged();
AES.KeySize = 256;
AES.BlockSize = 128;
var key = new Rfc2898DeriveBytes(passwords, salt, 50000);
AES.Key = key.GetBytes(AES.KeySize / 8);
AES.IV = key.GetBytes(AES.BlockSize / 8);
AES.Mode = CipherMode.CBC;
AES.Padding = PaddingMode.Zeros;
using (FileStream fsCrypt = new FileStream(inputFile + ".aes", FileMode.Create))
{
fsCrypt.Write(salt, 0, salt.Length);
using (CryptoStream cs = new CryptoStream(fsCrypt, AES.CreateEncryptor(), CryptoStreamMode.Write))
{
using (FileStream fsIn = new FileStream(inputFile, FileMode.Open))
{
byte[] buffer = new byte[1048576];
int read;
while ((read = fsIn.Read(buffer, 0, buffer.Length)) > 0)
{
cs.Write(buffer, 0, read);
}
}
}
}
}
we are using below code for decryption(Node js)
AESCrypt.encrypt = function(cryptkey, iv, cleardata) {
var encipher = crypto.createCipheriv('aes-256-cbc', cryptkey, iv);
return Buffer.concat([
encipher.update(cleardata),
encipher.final()
]);
}
function decrypted(){
var enc;
fs.readFile('./resource/test.pdf', function (err,data) {
if (err) {
return console.log(err);
}
var bufferenc = new Buffer.from(data);
var dec = AESCrypt.decrypt(cryptkey,iv, bufferenc);
console.log(dec);
// var buffer = new Buffer.from(dec);
fs.writeFileSync('./resource/decrypted.pdf',dec);
});
}
Unable to decrypt a pdf file Using 'aes-256-cbc' algorithm in node js
You can try this code to decrypt the pdf data, it's working for me with the C# code: