For AES-128-CBC Encryption/Decryption | PHP
To use CBC encryption, you also need to sort the $iv offset, as follows: AES-128-CBC encryption and decryption.
Here i used simple keys for the example, But Keys need to be generated using a cryptographically secure random number generator if you are using this in a production.
$iv = '1234567890123456'; // 16 byte
$key = '1234567890123456'; // 16 byte
function decode($str,$key,$iv)
{
return openssl_decrypt(base64_decode($str),"AES-128-CBC",$key,OPENSSL_RAW_DATA, $iv);
}
function encode($str,$key,$iv)
{
return base64_encode(openssl_encrypt($str,"AES-128-CBC",$key,OPENSSL_RAW_DATA, $iv));
}
echo "String: Hellow World !";
echo "<br/>Encrypted String: ";
echo encode("Hellow World !",$key,$iv);
echo "<br/>Decryped String: ";
echo decode("l3mMP/irpStRPTIfYsdZmg==",$key,$iv);
OUT PUT
String: Hellow World !
Encrypted String: l3mMP/irpStRPTIfYsdZmg==
Decryped String: Hellow World !
For AES-256-CBC Encryption/Decryption | PHP
function encrypt_decrypt($action, $string)
{
$output = false;
$encrypt_method = "AES-256-CBC";
$secret_key = '12345678901234561234567890123456'; // 32 byte
$secret_iv = '1234567890123456
'; // 16 byte $key = hash('sha256', $secret_key); $iv = substr(hash('sha256', $secret_iv), 0, 16); if ( $action == 'encrypt' ) { $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv); $output = base64_encode($output); } else if( $action == 'decrypt' ) { $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv); } return $output; } echo "String: Hellow World !"; echo "<br/>Encrypted String: "; echo encrypt_decrypt('encrypt', "Hellow World !"); echo "<br/>Decryped String: "; echo encrypt_decrypt('decrypt', "QkNZWjlab2pSTUtqVnMyMHlYeTV4dz09");
OUT PUT
String: Hellow World !
Encrypted String: QkNZWjlab2pSTUtqVnMyMHlYeTV4dz09
Decryped String: Hellow World !