简体   繁体   English

使用AES Crypto-JS进行加密解密在android webview中不起作用?

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

In a webview in my android app, I am trying to do encryption and decryption with Crypto-JS. 在我的android应用中的网络视图中,我正在尝试使用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. 我是javascript新手。 In my another app i am doing this in android and its working fine. 在我的另一个应用程序中,我正在android中执行此操作,并且工作正常。 But with jquery decryption is not working. 但是用jQuery解密是行不通的。 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. 我做错了什么吗?

The CryptoJS decrypt() function expects the ciphertext either to be OpenSSL formatted or be a speciel object. CryptoJS crypto decrypt()函数期望密文为OpenSSL格式或为特殊对象。

The only value that you need to set on the special object is the ciphertext property: 您需要在特殊对象上设置的唯一值是ciphertext属性:

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

Furthermore, decrypted is a WordArray. 此外, decrypted是WordArray。 You need to use stringify() to get a string out of it: 您需要使用stringify()来获取字符串:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM