Home > Mobile >  AES encryption using C# and decryption using Javascript
AES encryption using C# and decryption using Javascript

Time:06-19

I've got a set of functions for encrypting/decrypting on the server (C#), however I'd like to port the decryption piece to Javascript. Here's the C# decryption functions I've used previously in C# with a sample encrypted string, password and IV

I'm having trouble with the JavaScript decryption piece using Cryptojs. The result that comes back is unexpectedly an empty string.

var ciphertext = "0MuDwNoWBFjN/1anszbl0Cxkrwh9ahRwE3c61t7io2c=";
var key = "8beee7ac-42d1-4294-91b8-68cd032cf1e1";
var iv = "9bC_#$/- %@Kliz=-@qT";

var ciphertextWA = CryptoJS.enc.Hex.parse(ciphertext);
var keyWA = CryptoJS.enc.Utf8.parse(key);
var ivWA = CryptoJS.enc.Utf8.parse(iv);
var ciphertextCP = { ciphertext: ciphertextWA };

var decrypted = CryptoJS.AES.decrypt(
    ciphertextCP,
    keyWA,
{ iv: ivWA }
);
console.log(decrypted.toString(CryptoJS.enc.Utf8));

CodePudding user response:

The bugs are in the determination of IV and key. Both are derived from passwords using SHA512. In the case of the key the first 32 bytes (bytes 0-31) are used, in the case of the IV the 16 bytes following the first 32 bytes (bytes 32-47).

The fixed code is:

var ciphertext = "0MuDwNoWBFjN/1anszbl0Cxkrwh9ahRwE3c61t7io2c=";
var key = "8beee7ac-42d1-4294-91b8-68cd032cf1e1";
var iv = "9bC_#$/- %@Kliz=-@qT";

var ciphertextWA = CryptoJS.enc.Base64.parse(ciphertext);
var ciphertextCP = { ciphertext: ciphertextWA };

var keyHashWA = CryptoJS.SHA512("8beee7ac-42d1-4294-91b8-68cd032cf1e1");
var keyWA = CryptoJS.lib.WordArray.create(keyHashWA.words.slice(0, 32/4));
var ivHashWA = CryptoJS.SHA512("9bC_#$/- %@Kliz=-@qT");
var ivWA = CryptoJS.lib.WordArray.create(ivHashWA.words.slice(32/4, 48/4));

var decrypted = CryptoJS.AES.decrypt(
    ciphertextCP,
    keyWA,
    { iv: ivWA }
);
console.log(decrypted.toString(CryptoJS.enc.Utf8));
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js"></script>

  • Related