· 9 years ago · Sep 09, 2016, 01:34 PM
1function encrypt_decrypt($action, $string) {
2 $output = false;
3
4 $encrypt_method = "AES-256-CBC";
5 $secret_key = 'This is my secret key';
6 $secret_iv = 'This is my secret iv';
7
8 // hash
9 $key = hash('sha256', $secret_key);
10
11 // iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
12 $iv = substr(hash('sha256', $secret_iv), 0, 16);
13
14 if( $action == 'encrypt' ) {
15 $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
16 $output = base64_encode($output);
17 }
18 else if( $action == 'decrypt' ){
19 $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
20 }
21
22 return $output;
23}
24
25$plain_txt = "This is my plain text";
26echo "Plain Text = $plain_txtn";
27
28$encrypted_txt = encrypt_decrypt('encrypt', $plain_txt);
29echo "Encrypted Text = $encrypted_txtn";
30
31$decrypted_txt = encrypt_decrypt('decrypt', $encrypted_txt);
32echo "Decrypted Text = $decrypted_txtn";
33
34if( $plain_txt === $decrypted_txt ) echo "SUCCESS";
35else echo "FAILED";
36
37echo "n";