How to decrypt with CryptoJS using AES?

隐身守侯 提交于 2019-12-24 07:05:38

问题


As the question suggests, I can't seem to get a decrypted value correctly using the required options (AES, ECB Mode & 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...


回答1:


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/

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 :)

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.



来源:https://stackoverflow.com/questions/27171390/how-to-decrypt-with-cryptojs-using-aes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!