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

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...

Answers:

Answer

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.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.