I had a bit of trouble finding a how-to of how to encrypt and decrypt using RIJNDAEL, so I put together a quick example of how to using a non-blank IV.

However I did find a useful code snippet from Chilkat Software that helped me a lot of the way.

The only gotcha I found is that if you generate an RIJNDAEL 256 CBC key and IV using OpenSSL it will generate a 64-bit key and 32-bit IV, even though using PHP mcrypt it expects them both to be 32-bit. If you generate an AES 128 CBC key and IV though they’re the right length; I’m assuming the encryption is still 256 however.

openssl enc -aes-128-cbc -k [insert-passphrase-here] -P -md sha1

Which should generate something that looks like this:

iv =B33D526335805E2CB332CAEF643E0C07

Here is a sample PHP script to demonstate the encryption and decryption:


$text = 'Testing encryption';

$cipher = mcrypt_module_open(MCRYPT_RIJNDAEL_256, '', MCRYPT_MODE_CBC, '');
$iv_size = mcrypt_enc_get_iv_size($cipher);

$key = '12345678901234561234567890123456';
$iv =  '9532654BD781547023AB4FA7723F2FCD';

echo "<strong>IV:</strong> " . bin2hex($iv) . '<br />';
echo "<strong>Key:</strong> " . bin2hex($key) . '<br />';
echo '<strong>Before encryption:</strong> ' . $text . '<br />';

// Encrypt
if (mcrypt_generic_init($cipher, $key, $iv) != -1)
	$encrypted = mcrypt_generic($cipher, $text);

	echo '<strong>After encryption:</strong> ' . bin2hex($encrypted) . '<br />';

// Decrypt
if (mcrypt_generic_init($cipher, $key, $iv) != -1)
	$decrypted = mdecrypt_generic($cipher, $encrypted);

	echo '<strong>After decryption:</strong> ' . $decrypted . '<br />';
  • By: Andrew Kirkpatrick
  • In: PHP
  • Under: