· 6 years ago · Oct 20, 2019, 12:28 PM
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 */
11function encrypt_decrypt($action, $string) {
12 $output = false;
13
14 $encrypt_method = "AES-256-CBC";
15 $secret_key = 'This is my secret key';
16 $secret_iv = 'This is my secret iv';
17
18 // hash
19 $key = hash('sha256', $secret_key);
20
21 // iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
22 $iv = substr(hash('sha256', $secret_iv), 0, 16);
23
24 if ( $action == 'encrypt' ) {
25 $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
26 $output = base64_encode($output);
27 } else if( $action == 'decrypt' ) {
28 $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
29 }
30
31 return $output;
32}
33
34$plain_txt = "This is my plain text";
35echo "Plain Text =" .$plain_txt. "\n";
36
37$encrypted_txt = encrypt_decrypt('encrypt', $plain_txt);
38echo "Encrypted Text = " .$encrypted_txt. "\n";
39
40$decrypted_txt = encrypt_decrypt('decrypt', $encrypted_txt);
41echo "Decrypted Text =" .$decrypted_txt. "\n";
42
43if ( $plain_txt === $decrypted_txt ) echo "SUCCESS";
44else echo "FAILED";
45
46echo "\n";
47
48?>