PHP AES Encrypt string function


Make sure mcrypt is installed and enabled.
#ubuntu:
sudo apt-get install php5-mcrypt;
sudo php5enmod mcrypt; 
sudo service apache2 restart;#apache
php -r "print_r(mcrypt_list_algorithms());";  #cli
.
<?php
//see: http://php.net/manual/en/book.mcrypt.php
$key="9eAU3jgN_BsDAGAaOoAe_vOs1ZFD88Zv";
$original_string = "encrypt me";
$encrypted_hex_string = encryptStringAES($original_string, $key);
$decrypted_string = decryptStringAES($encrypted_hex_string, $key);
echo $original_string."\n";
echo $encrypted_hex_string."\n";
echo $decrypted_string."\n";
 
function encryptStringAES($string, $key)//$key expected to be ASCII string length 32
{
    $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
    $key_length = mcrypt_enc_get_key_size($td);
    $key = substr($key, 0, $key_length );
    $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_DEV_URANDOM );
    mcrypt_generic_init($td, $key, $iv);
    $encrypted_data_bin = mcrypt_generic($td, $string);
    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);
    $hmac = hash_hmac('sha1', $encrypted_data_bin, $key, $raw_output = true);
    $raw = $hmac.$iv.$encrypted_data_bin;
    $encrypted_string = str_replace( array('+','/','='), array('.','_','-'), base64_encode($raw) );
    return strlen($key)==$key_length ? $encrypted_string : '';
}
 
function decryptStringAES($encrypted_string, $key)
{
    $raw = base64_decode( str_replace( array('.','_','-'), array('+','/','='), $encrypted_string ) );
    $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
    $key_length = mcrypt_enc_get_key_size($td);
    $key = substr($key, 0, $key_length );
    $iv_size = mcrypt_enc_get_iv_size($td);
    $hmac_size = 20; //strlen(hash_hmac('sha1', ...));
    $hmac = substr($raw, 0, $hmac_size);
    $iv = substr($raw, $hmac_size, $iv_size);
    $encrypted_data_bin = substr($raw, $hmac_size + $iv_size);
    $calcmac = hash_hmac('sha1', $encrypted_data_bin, $key, $raw_output = true);
    mcrypt_generic_init($td, $key, $iv);
    $decrypted = mdecrypt_generic($td, $encrypted_data_bin);
    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);
    return $calcmac==$hmac ? rtrim($decrypted, "\0") : '';
}

code snippets are licensed under Creative Commons CC-By-SA 3.0 (unless otherwise specified)