oussama kamal
oussama kamal

Reputation: 1037

openssl_encrypt VS mcrypt_encrypt

I have to do AES 128 encryption in CBC mode and match it with the same AES encyption in coldfusion.

Here is my code in PHP:

function pkcs5_pad($text, $blocksize) {
    $pad = $blocksize - (strlen($text) % $blocksize);
    return $text . str_repeat(chr($pad), $pad);
}

$key = "vRJ6XSUi7OGebUK+n1vKkA==";
$iv = "AF9iPTpJC+zEa2auUxuloQ==";
$data = $this->pkcs5_pad("Message to encrypt", 16);
echo openssl_encrypt($data, 'aes-128-cbc', $key, 0, base64_decode($iv));
echo "<br>";
echo base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, base64_decode($iv)));

mcrypt_encrypt is depreciated but gives me the same compatible result as in coldfusion: qLz13+xk19lZjSbfs92Ze5akuDbWOsNF2rYZN7aaEHc= but openssl_encrypt gives me a diffrent value: dnEcUy2tmvLZhZclnEwRpYHEbHajzmkpwbPorfNw5eN4d37MadEiPGLPvNAZmW4Q

How can I make openssl_encrypt give the same value as mcrypt_encrypt does? Isn't it supposed to be a replacement for it?

Upvotes: 2

Views: 2312

Answers (1)

user149341
user149341

Reputation:

Two problems:

  1. You aren't Base64 decoding the key, so you're passing a 24-byte (= 192-bit) key to both openssl_encrypt and mcrypt_encrypt. Apparently, these functions interpret such a key in different ways! base64_decode the key first for consistent results.

    Alternatively, if you really want to use the Base64-encoded string as a 192-bit key, pass 'aes-192-cbc' as the method to openssl_encrypt(). This is what mcrypt is doing here. (Which is not the same as what would happen if you passed MCRYPT_RIJNDAEL_192 as the cipher -- that changes the block size, not the key size!)

  2. openssl_encrypt uses PKCS5 padding automatically. Padding the data before passing it to this function ends up making the data get padded twice, leaving it one block longer than intended.

With these problems fixed, both functions now give the same result.

Upvotes: 3

Related Questions