RIJNDAEL encryption with PHP, 256-bit using IV

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:

salt=DD740CB2ABBE8C3A 
key=23FA93B1A2E5CE60E7F456F9EFC9FE75 
iv =B33D526335805E2CB332CAEF643E0C07

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

<?php

$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);
	mcrypt_generic_deinit($cipher);

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

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

	echo '<strong>After decryption:</strong> ' . $decrypted . '<br />';
}

13 comments

Leave a Reply to Vasiq Mz Cancel reply