Search code examples
javascriptencryptioncryptojs

CryptoJS.AES.decrypt failure reasons?


The CryptoJS.AES.decrypt function is returning an empty WordArray.

My parameters are secret, key, and iv. key is a 256 bit WordArray and is confirmed to be correct, iv is a 128 bit WordArray and also confirmed to be correct.

secret is encrypted using php's openssl_encrypt() - the plaintext is 32 bytes - the result is 48 bytes (so it seems to be padding correctly).

I've tried secret as a WordArray, Hex string and base64 string but when I call:

var decrypted = CryptoJS.AES.decrypt(secret, key, {iv: iv});

decrypted is an empty WordArray. It's driving me mad... What is failing? I would think the error is in secret somewhere, with padding formats or something weird, but Cryptojs and openssl_(encrypt/decrypt) have proved to be compatible with each other for me before. Please help before I lose my mind.


Solution

  • OK, so the key to this was that the docs for CryptoJS.AES.decrypt(message, key, {iv:iv}) say that you can feed a WordArray, Hex, or Base64 for the message argument. This doesn't seem to be true.

    The only way I can get it to work was by giving it a Base64 string to work with.

    key and iv must still be WordArray

    *When I tried Base64 strings in my hours of monkeying, I must not have changed the output on the server to actually send Base64 - so there you go.

    Thanks to @CodesInChaos for bringing up endianess, though. It started me messing with the encodings again.

    ...Now to clean up all those console.log()'s and var_dump()'s strewn about the code...