1

I'm working on a project that uses an external API that is written in C#. In this API, I need to send some encrypted data while using their key that was provided when I started a session.

My project is built using NodeJS, so to do this encryption I am using the CryptoJS module. While talking with the API developer, he sent me a code showing how the encryption is made in C#. Here is the code with an example key and value to be encrypted.

    TripleDESCryptoServiceProvider mDes = new TripleDESCryptoServiceProvider();
    mDes.Key = Convert.FromBase64String("bv8czu/UPuZg6xNxnJAD/vRtbng9mQZX");
    mDes.Mode = CipherMode.ECB;
    mDes.Padding = PaddingMode.Zeros;
    ICryptoTransform mDesEnc = mDes.CreateEncryptor();
    byte[] data = Encoding.UTF8.GetBytes("1"); //value to encrypt
    var crypto = Convert.ToBase64String(mDesEnc.TransformFinalBlock(data, 0, data.Length));
    Console.WriteLine(crypto);

This results in the following encryption: 3EAaQjY2dgA=

As you can see in the code or running it, the encryption uses 3DES, mode ECB, Zero Padding and the key while in a byte array format has 24 bytes.

So I started to recreate this code in JavaScript and ended up with this:

    var CryptoJS = require("crypto-js");
    var encryptStringWith3DES = function(toEncrypt, key){
        toEncrypt = "1";
        key = "bv8czu/UPuZg6xNxnJAD/vRtbng9mQZX";
        key = CryptoJS.enc.Utf8.parse(key);

        console.log(toEncrypt + "     " + key);

        var encrypted = CryptoJS.TripleDES.encrypt(toEncrypt, key,{
            mode: CryptoJS.mode.ECB,
            padding: CryptoJS.pad.ZeroPadding
        }).toString();

        console.log(encrypted);
    }

And it results in the following encryption: dj1byXBV6ug=

I have searched for many answers and none worked. My suspicion is with how CryptoJS receives the key as a parameter and how the key and data are parsed.

Does any of you know how to make my JS code result in the same encrypted data as the C# one?

0 Answers0