0

I am trying to replicate this C# function into a NodeJS function.

Here is the C# function first.

private byte[] Decrypt(byte[] plainText)
        {
            using (var aes = new AesManaged())
            {
                aes.Mode = CipherMode.ECB;
                aes.Padding = PaddingMode.Zeros;

                var decryptor = aes.CreateDecryptor(Key, Key);
                var decrypted = decryptor.TransformFinalBlock(plainText, 0, plainText.Length);

                return decrypted;
            }
        } 

And here is the NodeJS function that I am trying to convert it to.

var crypto = require("crypto")
require('./config');

function decrypt(key, data) {
        var decipher = crypto.createDecipher('aes-256-ecb', key);
        var decrypted = decipher.update(data, "utf8", "utf8");
        decipher.setAutoPadding(true);
        decrypted += decipher.final('utf8');

        return decrypted;
}

decryptedText = decrypt(process.env.password, process.env.encryptedMessage);
console.log("Decrypted Text: ",  decryptedText);

The NodeJS function is wrong can someone convert the C# function into a NodeJS function as I have limited experience with this as I am a frontend developer.

Currently the output that I am getting is:

Error: error:0606506D:digital envelope routines:EVP_DecryptFinal_ex:wrong final block length
    at Error (native)
    at Decipher.Cipher.final (crypto.js:158:26)
    at decrypt (/Users/dave/Tests/sqs-consumer/app3.js:8:31)
Dave
  • 332
  • 1
  • 5
  • 23
  • what is the type of data in node? You need to encode it to base64 I guess, see the docs for [decipher.update](https://nodejs.org/api/crypto.html#crypto_decipher_update_data_inputencoding_outputencoding) – Mat J Sep 18 '17 at 10:53
  • @MatJ the type of data is a encrypted and compressed string. I first have to decrypt the string and then extract it. – Dave Sep 18 '17 at 11:03
  • 1
    If you read that link I provided, you'll know that if you pass a string rather than buffer, then the second argument needs to be one of the three values, `latin1`, `base64` or `hex` – Mat J Sep 18 '17 at 11:24
  • 1
    1. Do not use ECB mode in new work and update legacy work ASAP, it is not secure, see [ECB mode](https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Electronic_Codebook_.28ECB.29), scroll down to the Penguin. Instead use CBC mode with a random IV, just prefix the encrypted data with the IV for use in decryption, it does not need to be secret. 2. Zeto padding mode is non-standard and can not be used for binary data. The generally used padding is PKCS#7 (née PKCS#5). – zaph Sep 18 '17 at 14:18

0 Answers0