· 7 years ago · Dec 15, 2018, 01:44 AM
1<?php
2/**
3 * Powerful 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 $secret_key = 'This is my secret key';
13 $cipher = "AES-256-CBC";
14 $ivlen = openssl_cipher_iv_length( $cipher );
15
16 if ( $action == 'encrypt' ) {
17 $iv = openssl_random_pseudo_bytes( $ivlen );
18 $ciphertext_raw = openssl_encrypt( $string, $cipher, $secret_key, $options = OPENSSL_RAW_DATA, $iv );
19 $hmac = hash_hmac( 'sha512', $ciphertext_raw, $secret_key, $as_binary = true );
20 $ciphertext = base64_encode( $iv.$hmac.$ciphertext_raw );
21
22 return $ciphertext;
23 } else if( $action == 'decrypt' ) {
24 $c = base64_decode( $string );
25 $iv = substr( $c, 0, $ivlen );
26 $hmac = substr( $c, $ivlen, $sha2len = 64 );
27 $ciphertext_raw = substr( $c, $ivlen+$sha2len );
28 $original_plaintext = openssl_decrypt( $ciphertext_raw, $cipher, $secret_key, $options = OPENSSL_RAW_DATA, $iv );
29 $calcmac = hash_hmac( 'sha512', $ciphertext_raw, $secret_key, $as_binary = true );
30
31 //PHP 5.6+ timing attack safe comparison
32 if ( hash_equals( $hmac, $calcmac ) )
33 return $original_plaintext;
34 else
35 false;
36 }
37}
38
39$plain_txt = "This is my plain text";
40echo "Plain Text = " .$plain_txt. "\n";
41$encrypted_txt = encrypt_decrypt( 'encrypt', $plain_txt );
42echo "Encrypted Text = " .$encrypted_txt. "\n";
43$decrypted_txt = encrypt_decrypt( 'decrypt', $encrypted_txt );
44echo "Decrypted Text =" .$decrypted_txt. "\n";
45if ( $plain_txt === $decrypted_txt ) echo "SUCCESS";
46else echo "FAILED";
47echo "\n";
48?>