· 8 years ago · Feb 01, 2018, 11: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,$secret_key = "supersecret_key") {
12 $output = false;
13 $encrypt_method = "AES-256-CBC";
14 $secret_iv = 'randomString#12231'; // change this to one more secure
15 $key = hash('sha256', $secret_key);
16
17 // iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
18 $iv = substr(hash('sha256', $secret_iv), 0, 16);
19 if ( $action == 'encrypt' ) {
20 $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
21 $output = base64_encode($output);
22 } else if( $action == 'decrypt' ) {
23 $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
24 }
25 return $output;
26}
27
28// dinamic string
29$dynamic_string = "TOKEN_GEDUCAR#".date("Y-m-d H");
30$secret_key = "847EJDALQIS2PE3UDKA7128409EJA"; // same in the connected applications
31
32echo "<pre>";
33echo "String Token:". $dynamic_string."\n";
34
35// encrypt string
36$encrypted_string = encrypt_decrypt('encrypt',$dynamic_string,$secret_key);
37echo "Encrypted String:". $encrypted_string."\n";
38
39//decrypt string
40$decrypted_string = encrypt_decrypt('decrypt',$encrypted_string,$secret_key);
41echo "Decrypted string:". $decrypted_string."\n";
42
43// al final comparar el string desencriptado con el string dinamico
44if($dynamic_string==$decrypted_string){
45 echo "Correct authentication\n";
46}
47
48echo "</pre>";