0

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.

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
Piscean
  • 3,069
  • 12
  • 47
  • 96

1 Answers1

2

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);
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
  • i am encrypting 11 and i am getting ZWdyZXRhaWxtYWhtb29kaA==ABany8H/x7GbIMcta5o9Zg== as encrypted string. but when i decrypt it with your code then i get 33313332 . Why didn't i get 11 back – Piscean Jun 16 '15 at 14:44