· 7 years ago · Jul 20, 2018, 09:42 PM
1<?php
2
3function encrypt_decrypt($action, $string) {
4 $output = false;
5 $encrypt_method = "AES-256-CBC";
6 $secret_key = 'This is my secret key';
7 $secret_iv = 'This is my secret iv';
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 if ( $action == 'encrypt' ) {
14 $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
15 $output = base64_encode($output);
16 } else if( $action == 'decrypt' ) {
17 $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
18 }
19 return $output;
20}
21$plain_txt = "This is my plain text";
22echo "Plain Text =" .$plain_txt. "\n";
23$encrypted_txt = encrypt_decrypt('encrypt', $plain_txt);
24echo "Encrypted Text = " .$encrypted_txt. "\n";
25$decrypted_txt = encrypt_decrypt('decrypt', $encrypted_txt);
26echo "Decrypted Text =" .$decrypted_txt. "\n";
27if ( $plain_txt === $decrypted_txt ) echo "SUCCESS";
28else echo "FAILED";
29echo "\n";