-1

I have a problem when decrypting (using CryptoJs) my PHP encrypted data. Here is my PHP encryption:

function encrypt($pure_string, $encryption_key, $iv) {
    $encrypted_string = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $encryption_key, utf8_encode($pure_string), MCRYPT_MODE_CBC, $iv);
    return $encrypted_string;
}

function cripto()
{
    $crypto_key = "230e8cb8c43d532f389ff0e2b5337919";
    $data_to_encrypt = "Data to encrypt";

    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);

    $ciphertext = $this->encrypt($data_to_encrypt, $crypto_key, $iv);
    return array("iv" => pack('H*', $iv), "chipertext" => base64_encode($ciphertext),"key" => $crypto_key);

}

And here is my JavaScript code (the result of php crypto function is stored in encrypted variable):

var ciphertext = <?php echo '"'.$encrypted["ciphertext"].'"'; ?>;
var iv = <?php echo '"'.$encrypted["iv"].'"'; ?>;
var crypto_key = <?php echo '"'.$encrypted["key"].'"'; ?>;

iv = CryptoJS.enc.Hex.parse(iv);
ciphertext = CryptoJS.enc.Base64.parse(ciphertext);

var decrypted = CryptoJS.AES.decrypt(ciphertext, crypto_key,{ iv: iv });
console.log(decrypted.toString(CryptoJS.enc.Utf8));

My decrypted value is always an empty string and I can't figure out why.

mihaela
  • 394
  • 2
  • 12

1 Answers1

1

You have two problems:

  • PHP uses Zero padding (padding of 0-15 bytes of 0x00), but CryptoJS uses PKCS#7 padding by default. Those are incompatible.
  • CryptoJS' decrypt() function expects a CipherParams object which you can simply emulate by passing an object with the ciphertext property set.

Together:

iv = CryptoJS.enc.Hex.parse(iv);
ciphertext = CryptoJS.enc.Base64.parse(ciphertext);

var decrypted = CryptoJS.AES.decrypt({ ciphertext: ciphertext }, crypto_key, {
    iv: iv,
    padding: CryptoJS.pad.ZeroPadding
});
console.log(decrypted.toString(CryptoJS.enc.Utf8));

Don't forget to include pad-zeropadding-min.js.


Keep in mind that JavaScript cryptography has its problems for justification. You really should be using SSL, because without SSL, this is just obfuscation (key is sent along with the ciphertext).

It would be better to do the PKCS#7 padding in PHP and keep the default in CryptoJS.

Community
  • 1
  • 1
Artjom B.
  • 61,146
  • 24
  • 125
  • 222