Encryption in C# Decryption in JS (CryptoJS)

bman picture bman · Sep 15, 2016 · Viewed 8.3k times · Source

I do not get the same result on CryptoJS. May you please check what is wrong?

Here is my expected input/outputs:

Encrypted String: 723024D59CF7801A295F81B9D5BB616E
Decrypted String: stackoverflow

Here are my Decryption/Encryption methods in C# . Encryption is TripleDES mode CBC, I am using the same key and iv on the CryptoJS code.

public static string Encrypt(string data, string key, string iv)
{
    byte[] bdata = Encoding.ASCII.GetBytes(data);
    byte[] bkey = HexToBytes(key);
    byte[] biv = HexToBytes(iv);

    var stream = new MemoryStream();
    var encStream = new CryptoStream(stream,
        des3.CreateEncryptor(bkey, biv), CryptoStreamMode.Write);

    encStream.Write(bdata, 0, bdata.Length);
    encStream.FlushFinalBlock();
    encStream.Close();

    return BytesToHex(stream.ToArray());
}

public static string Decrypt(string data, string key, string iv)
{
    byte[] bdata = HexToBytes(data);
    byte[] bkey = HexToBytes(key);
    byte[] biv = HexToBytes(iv);

    var stream = new MemoryStream();
    var encStream = new CryptoStream(stream,
        des3.CreateDecryptor(bkey, biv), CryptoStreamMode.Write);

    encStream.Write(bdata, 0, bdata.Length);
    encStream.FlushFinalBlock();
    encStream.Close();

    return Encoding.ASCII.GetString(stream.ToArray());
}

Here is how I do the decryption using CryptoJS

var key = "90033E3984CEF5A659C44BBB47299B4208374FB5DC495C96";
var iv = "E6B9AFA7A282A0CA";

key = CryptoJS.enc.Hex.parse(key);
iv = CryptoJS.enc.Hex.parse(iv);


// Input is a Hex String
var decrypted = CryptoJS.TripleDES.decrypt('723024D59CF7801A295F81B9D5BB616E', key, { iv : iv, mode:CryptoJS.mode.CBC});
console.log(decrypted.toString());

Answer

Artjom B. picture Artjom B. · Sep 15, 2016

CryptoJS expects the ciphertext to be a CipherParams object or an OpenSSL-encoded string. You've passed in the ciphertext as Hex. Do this instead:

var decrypted = CryptoJS.TripleDES.decrypt({
    ciphertext: CryptoJS.enc.Hex.parse('723024D59CF7801A295F81B9D5BB616E')
}, key, { 
    iv : iv, 
    mode:CryptoJS.mode.CBC
});

decrypted is now a WordArray object. Stringifying it leads to a string with the default encoding which is Hex. If you know that you should get text out, you can use the appropriate encoding like:

console.log(decrypted.toString(CryptoJS.enc.Utf8));