· 4 years ago · Dec 07, 2020, 05:22 PM
1<?php
2function stringEncryption($action, $string){
3 $output = false;
4 $encrypt_method = 'AES-256-CBC'; // Default
5 $secret_key = '63CE1C3557BC8E0E1063CE15406C91A3'; // Change the key!
6 $secret_iv = '72D49D98E177A39916A4B027B70ACC8A'; // Change the init vector!
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 return $output;
22}
23
24/* Example */
25echo '<pre>';
26$info = 'V132145';
27echo 'info = '.$info."\n";
28$encrypted = stringEncryption('encrypt', $info);
29echo 'encrypted = '.$encrypted."\n";
30$decrypted = stringEncryption('decrypt', $encrypted);
31echo 'decrypted = '.$decrypted."\n";
32echo '</pre>';
33?>