There are some troubles implementing a 1:1 encryprion/decription between mcrypt and openssl using MCRYPT_RIJNDAEL_128 CBC because the AES-256 is different from RIJNDAEL-256.
The 256 in AES refers to the key size, where the 256 in RIJNDAEL refers to block size.
AES-256 is RIJNDAEL-128 when used with a 256 bit key
(https://stackoverflow.com/questions/6770370/aes-256-encryption-in-php ircmaxell Jun 22 '13 at 11:50)
Example
<?php
function encrypt_openssl($msg, $key, $iv) {
$encryptedMessage = openssl_encrypt($msg, 'AES-256-CBC', $key, OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING , $iv);
return $iv . $encryptedMessage;
}
function decrypt_openssl($data, $key) {
$iv_size = openssl_cipher_iv_length('AES-256-CBC');
$iv = substr($data, 0, $iv_size);
$data = substr($data, $iv_size);
return openssl_decrypt($data, 'AES-256-CBC', $key,OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING , $iv);
}
function decrypt_data($data,$key) {
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$iv = substr($data, 0, $iv_size);
$data = substr($data, $iv_size);
$decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, $iv);
$decrypted = rtrim($decrypted, chr(0));
return($decrypted);
}
function encrypt_data($data,$key,$iv) {
$encrypted = $iv . mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, $iv);
return $encrypted;
}
function pad_zero($data) {
$len = mcrypt_get_block_size (MCRYPT_RIJNDAEL_128,MCRYPT_MODE_CBC);
if (strlen($data) % $len) {
$padLength = $len - strlen($data) % $len;
$data .= str_repeat("\0", $padLength);
}
return $data;
}
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$data = "Hello World!";
$key = hash('sha256',"secret",true);
echo "\n\n$data\n\n";
$enc = base64_encode(encrypt_data($data,$key,$iv));
echo "\nEnc: $enc";
$dec = decrypt_data(base64_decode($enc),$key);
echo "\nDec: $dec";
$dec2=decrypt_openssl(base64_decode($enc),$key);
echo "\nDec: $dec2";
echo "\n\nreverse\n";
$enc2 = base64_encode(encrypt_openssl(pad_zero($data),$key,$iv));
echo "\nEnc: $enc2";
$dec = decrypt_data(base64_decode($enc2),$key);
echo "\nDec: $dec";
$dec2=decrypt_openssl(base64_decode($enc2),$key);
echo "\nDec: $dec2";