· 6 years ago · Apr 28, 2019, 08:06 AM
1<?php
2/**
3 * simple method to encrypt or decrypt a plain text string
4 * initialization vector(IV) has to be the same when encrypting and decrypting
5 *
6 * @param string $action: can be 'encrypt' or 'decrypt'
7 * @param string $string: string to encrypt or decrypt
8 *
9 * @return string
10 */
11 function encrypt_decrypt($action, $string) {
12 $output = false;
13 $encrypt_method = "AES-256-CBC";
14 $secret_key = '!@#wefvb#$@%';
15 $secret_iv = 'AgHyE5$3HoPu*&7';
16 // hash
17 $key = hash('sha256', $secret_key);
18
19 // iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
20 $iv = substr(hash('sha256', $secret_iv), 0, 16);
21 if ( $action == 'encrypt' ) {
22 $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
23 $output = base64_encode($output);
24 } else if( $action == 'decrypt' ) {
25 $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
26 }
27 return $output;
28 }
29
30echo encrypt_decrypt('encrypt', 'lucas_gay');
31
32echo "<br>";
33
34echo encrypt_decrypt("decrypt", "RkJuZE9McUhSZGtKS2ZoZi9EZ1pUdz09");