AES-256 decryption with PHP & Mcrypt

I’ve recently had to decrypt some data from a third party API, encrypted with AES-256.

Thanks to an example implementation only in C# and a quirk of PHP, I stumbled for quite a while.

AES-256 is a derivation of the Rijndael cipher, but the two are not quite the same. Mcrypt only lists MCRYPT_RIJNDAEL_128, MCRYPT_RIJNDAEL_192 and MCRYPT_RIJNDAEL_256 – no AES.

I did try checking out PHP’s OpenSSL ( >=PHP 5.3), where an example on the page lists aes-256-cbc as a supported standard, but despite the documentation and examples listing up to 5 arguments, the last being the crucial (in this implementation) Initialisation Vector, PHP was throwing an error, claiming OpenSSL could take a maximum of 4 arguments, leaving me to have the final argument with the internet and looking like a nutter in the office.

Some feedback from the API developers firmed up what I was dealing with and spurred me to another bout of research

Cipher settings provided by the API Developers

Critically this confirmed I should be using MCRYPT_MODE_CBC

Finally I found this post: AES-256 using PHP-mcrypt which cleared up the crucial issue – AES-256 support IS possible with mcrypt – by using MCRYPT_RIJNDAEL_128.

Oh of course, how obvious. Silly me…

So, here is a very simple implementation of AES-256 as a CodeIgniter class, which outputs the decrypted data to screen:

Leave a Reply

Your e-mail address will not be published. Required fields are marked *