Search This Blog

Wednesday, March 7, 2018

PHP - Aes-256-cbc Encrypt Decrypt with IV vector


function encrypt_decrypt($action, $string) {
    $output = false;
    $encrypt_method = "aes-256-cbc";
    $secret_key = 'abcdefghi1234567890';
    $secret_iv = '';
 
// hash
    $key = hash('sha256', $secret_key);
    echo "

".$key;

    // iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
    $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;
}
$plain_txt = "I am vijay";
echo "

Plain Text =" .$plain_txt. "\n";
$encrypted_txt = encrypt_decrypt('encrypt', $plain_txt);
echo "

Encrypted Text = " .$encrypted_txt. "\n";

$decrypted_txt = encrypt_decrypt('decrypt', $encrypted_txt);
echo "

Decrypted Text =" .$decrypted_txt. "\n";

if ( $plain_txt === $decrypted_txt ) echo "

SUCCESS";
else echo "

FAILED";
echo "\n";

?>



Output

Plain Text =I am vijay

681448fb66d8704c7d52f6770f6087882db21c899fe48d21012a587bbe70cdd3

Encrypted Text = THRtUkJYWFUzb1NzUFRoOUw5T3Q2UT09

681448fb66d8704c7d52f6770f6087882db21c899fe48d21012a587bbe70cdd3

Decrypted Text =I am vijay

SUCCESS

No comments:

Hit Counter


View My Stats