| 1 |
<?php |
| 2 |
|
| 3 |
namespace FluentForm\App\Helpers; |
| 4 |
|
| 5 |
class Protector |
| 6 |
{ |
| 7 |
/** |
| 8 |
* Get the salt for the encryption and decryption. |
| 9 |
*/ |
| 10 |
public static function getSalt() |
| 11 |
{ |
| 12 |
$salt = get_option('_fluentform_security_salt'); |
| 13 |
|
| 14 |
if (!$salt) { |
| 15 |
$salt = wp_generate_password(); |
| 16 |
|
| 17 |
update_option('_fluentform_security_salt', $salt, 'no'); |
| 18 |
} |
| 19 |
|
| 20 |
return $salt; |
| 21 |
} |
| 22 |
|
| 23 |
/** |
| 24 |
* Encryp a text using a predefined salt. |
| 25 |
* |
| 26 |
* @param string $text |
| 27 |
* |
| 28 |
* @return string $text |
| 29 |
*/ |
| 30 |
public static function encrypt($text) |
| 31 |
{ |
| 32 |
$key = static::getSalt(); |
| 33 |
|
| 34 |
$cipher = 'AES-128-CBC'; |
| 35 |
|
| 36 |
$ivlen = openssl_cipher_iv_length($cipher); |
| 37 |
|
| 38 |
$iv = openssl_random_pseudo_bytes($ivlen); |
| 39 |
|
| 40 |
$ciphertext_raw = openssl_encrypt($text, $cipher, $key, $options = OPENSSL_RAW_DATA, $iv); |
| 41 |
|
| 42 |
$hmac = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary = true); |
| 43 |
|
| 44 |
return base64_encode($iv . $hmac . $ciphertext_raw); |
| 45 |
} |
| 46 |
|
| 47 |
/** |
| 48 |
* Decrypt a text using a predefined salt. |
| 49 |
* |
| 50 |
* @param string $text |
| 51 |
* |
| 52 |
* @return string $text |
| 53 |
*/ |
| 54 |
public static function decrypt($text) |
| 55 |
{ |
| 56 |
$key = static::getSalt(); |
| 57 |
|
| 58 |
$c = base64_decode($text); |
| 59 |
|
| 60 |
$cipher = 'AES-128-CBC'; |
| 61 |
|
| 62 |
$ivlen = openssl_cipher_iv_length($cipher); |
| 63 |
|
| 64 |
$iv = substr($c, 0, $ivlen); |
| 65 |
|
| 66 |
$hmac = substr($c, $ivlen, $sha2len = 32); |
| 67 |
|
| 68 |
$ciphertext_raw = substr($c, $ivlen + $sha2len); |
| 69 |
|
| 70 |
$original_plaintext = openssl_decrypt($ciphertext_raw, $cipher, $key, $options = OPENSSL_RAW_DATA, $iv); |
| 71 |
|
| 72 |
$calcmac = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary = true); |
| 73 |
|
| 74 |
if (hash_equals($hmac, $calcmac)) { // timing attack safe comparison |
| 75 |
return $original_plaintext; |
| 76 |
} |
| 77 |
} |
| 78 |
} |
| 79 |
|