AES-256 encryption in PHP

mariannnn picture mariannnn · Jul 21, 2011 · Viewed 65.3k times · Source

I need a PHP function, AES256_encode($dataToEcrypt) to encrypt the $data into AES-256 and another one AES256_decode($encryptedData) do the opposite. Does anyone know what code should this functions have?

Answer

Fabio picture Fabio · Jul 21, 2011

Look at the mcrypt module

AES-Rijndael example taken from here

$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($iv_size, MCRYPT_DEV_URANDOM);
$key = pack('H*', "bcb04b7e103a0cd8b54763051cef08bc55abe029fdebae5e1d417e2ffb2a00a3");
# show key size use either 16, 24 or 32 byte keys for AES-128, 192
# and 256 respectively
$key_size =  strlen($key);
echo "Key size: " . $key_size . "\n";
$text = "Meet me at 11 o'clock behind the monument.";
echo strlen($text) . "\n";

$crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $text, MCRYPT_MODE_CBC, $iv);
echo strlen($crypttext) . "\n";

This is the decrypt function