Encryption decryption with AES Crypto-JS does not work in an android webview?

1.9k views Asked by At

In a webview in my android app, I am trying to do encryption and decryption with Crypto-JS. Encryption is working fine but decryption does not work. I searched a lot and none of the solution i found worked for me. I am new with javascript. In my another app i am doing this in android and its working fine. But with jquery decryption is not working. Following is the Encryption function I am using:

function encryptText(textvalue, key) {
    var key = CryptoJS.enc.Utf8.parse(key);
    var iv = CryptoJS.lib.WordArray.random(128/8);

    var encrypted = CryptoJS.AES.encrypt(textvalue, key,
       {
          keySize: 128 / 8,
          iv: iv,
          mode: CryptoJS.mode.CBC,
          padding: CryptoJS.pad.Pkcs7
       });

    var pass = encrypted.ciphertext.toString(CryptoJS.enc.Base64);
    var ivpass = encrypted.iv.toString(CryptoJS.enc.Base64);

    return ivpass+pass;
}

Its working fine. Following is the descryption function I am using:

function decryptText(encrypted, keyParam){
    var key = CryptoJS.enc.Utf8.parse(keyParam);
    var indexOfSeperation = encrypted.indexOf("=="); 

    var iv = encrypted.substring(0, indexOfSeperation+2);
    var value = encrypted.substring(indexOfSeperation + 2);
    console.log("iv: "+iv);
    console.log("value: "+value);

    var valueStr  = CryptoJS.enc.Base64.parse(value);
    var ivStr  = CryptoJS.enc.Base64.parse(iv);

    var decrypted = CryptoJS.AES.decrypt(valueStr, key,
       {
          iv: ivStr,
          mode: CryptoJS.mode.CBC,
          padding: CryptoJS.pad.Pkcs7
       }
   );

   var result = CryptoJS.enc.Utf8.parse(decrypted);
   console.log("result: "+result);
}

result is always empty. Is there anything I am doing wrong.

1

There are 1 answers

1
Artjom B. On BEST ANSWER

The CryptoJS decrypt() function expects the ciphertext either to be OpenSSL formatted or be a speciel object.

The only value that you need to set on the special object is the ciphertext property:

var decrypted = CryptoJS.AES.decrypt({
        ciphertext: valueStr
    }, 
    key,
    {
        iv: ivStr,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    }
);

Furthermore, decrypted is a WordArray. You need to use stringify() to get a string out of it:

var result = CryptoJS.enc.Utf8.stringify(decrypted);