简体   繁体   English

如何使用AES使用CryptoJS解密?

[英]How to decrypt with CryptoJS using AES?

As the question suggests, I can't seem to get a decrypted value correctly using the required options (AES, ECB Mode & PKCS7). 正如问题所暗示的那样,使用所需的选项(AES,ECB模式和PKCS7),我似乎无法正确获得解密后的值。

I'm encrypting as below: 我正在加密如下:

  var ENC_KEY = "bXlrZXk=";  //"mykey"

  var encrypted = CryptoJS.AES.encrypt("hello",  CryptoJS.enc.Base64.parse(ENC_KEY), 
    {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    });
  console.log('encrypted: ' + encrypted);

which works as expected and outputs the encrypted value I expect however when I decrypt this using the below, I end up with an empty object being output: 它按预期工作并输出我期望的加密值,但是当我使用以下方法解密它时,最终输出的是一个空对象:

var decrypted = CryptoJS.AES.decrypt(encrypted, CryptoJS.enc.Base64.parse(ENC_KEY), 
    {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    });
    console.log('decrypted: ' + decrypted);

I have also tried using: 我也尝试过使用:

console.log('encrypted is decrypted to: ' + decrypted.toString(CryptoJS.enc.Utf8);

but no joy... 但没有喜悦

I tried this in a fiddle(modded a bit to get it to work): 我在一个小提琴中尝试了一下(对其进行了一些修改以使其起作用):

//decrypt gives a hex
function hex2a(hexx) {
    var hex = hexx.toString();//force conversion
    var str = '';
    for (var i = 0; i < hex.length; i += 2)
        str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
    return str;
}

var key = CryptoJS.enc.Base64.parse("Secret Passphrase"); 

alert(key);

var encrypted = CryptoJS.AES.encrypt("hello",  key, 
    {
        mode: CryptoJS.mode.ECB
    });

alert('encrypted: ' + encrypted);

var decrypted = CryptoJS.AES.decrypt(encrypted, key, 
    {
        mode: CryptoJS.mode.ECB
    });

alert('decrypted: ' + hex2a(decrypted));

http://jsfiddle.net/gttL705r/ http://jsfiddle.net/gttL705r/

and found that decrypt returned a hex, which may not have been a string... could this be causing your problems? 并发现解密返回了一个十六进制(可能不是字符串)……这可能会导致您的问题吗? So, with a quick hex2ascii function, 'hello' is return back :) 因此,通过快速的hex2ascii函数,'hello'返回了:)

I also removed the padding specified, since Pkcs7 is said to be the default in the docs and I couldn't find src js i needed to download for it. 我还删除了指定的填充,因为据说Pkcs7是文档中的默认设置,但我找不到我需要下载的src js。

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

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