Can't decrypt string with CryptoJS

萝らか妹 提交于 2019-11-30 12:01:43

I have been messing with this a while and I think I have found your problem. The main problem is this line encrypted.ciphertext.toString(). What you want is just encrypted.toString().

The toString function is defined for this object by CryptoJS and it returns the encrypted message that can be sent around safely. So if we change that we will have something like this:

var encrypted = CryptoJS.AES.encrypt(
  message,
  key,
  {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  }
);
console.log('            encrypted: '+encrypted.toString());

This will output Pw5ZDSYX3HAHuJNQvVkECQ== instead of 3f0e590d2617dc7007b89350bd590409. The reason your second function is working is because it doesn't use encrypted.ciphertext.toString() it just uses the actual object so no changes on that one. For the last one we will have the change the wrong text you were using to the new text that is returned without the ciphertext part but we also have to remove the CryptoJS.enc.Hex.parse. I don't really know what you were doing here but I can investigate if you meant something by that.

var manual_data = 'Pw5ZDSYX3HAHuJNQvVkECQ==';
var decrypted = CryptoJS.AES.decrypt(
  manual_data,
  key,
  {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  }
);
console.log('   decrypted, by hand: '+decrypted.toString(CryptoJS.enc.Utf8));

This should log the right stuff.

I have even created a JSBin for this. It is my first time using JSBin so I hope I did it right.

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