· 7 years ago · Oct 02, 2018, 07:18 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 $encrypt_method = "AES-256-CBC";
14 $secret_key = 'This is my secret key';
15 $secret_iv = 'This is my secret iv';
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$plain_txt = "This is my plain text";
30echo "Plain Text =" .$plain_txt. "\n";
31$encrypted_txt = encrypt_decrypt('encrypt', $plain_txt);
32echo "Encrypted Text = " .$encrypted_txt. "\n";
33$decrypted_txt = encrypt_decrypt('decrypt', $encrypted_txt);
34echo "Decrypted Text =" .$decrypted_txt. "\n";
35if ( $plain_txt === $decrypted_txt ) echo "SUCCESS";
36else echo "FAILED";
37echo "\n";
38?>