| 1 |
<?php |
| 2 |
/** |
| 3 |
* Encryptor implementation. |
| 4 |
* |
| 5 |
* @package SeQura\WC |
| 6 |
*/ |
| 7 |
|
| 8 |
namespace SeQura\WC\Core\Implementation\BusinessLogic\Utility; |
| 9 |
|
| 10 |
use SeQura\Core\BusinessLogic\Utility\EncryptorInterface; |
| 11 |
|
| 12 |
/** |
| 13 |
* Encryptor implementation. |
| 14 |
*/ |
| 15 |
class Encryptor implements EncryptorInterface { |
| 16 |
|
| 17 |
/** |
| 18 |
* Get key used for encryption and decryption. |
| 19 |
*/ |
| 20 |
private function get_key(): string { |
| 21 |
return hash( 'sha256', AUTH_KEY, true ); |
| 22 |
} |
| 23 |
|
| 24 |
/** |
| 25 |
* Encrypts a given string. |
| 26 |
* |
| 27 |
* @param string $data |
| 28 |
*/ |
| 29 |
public function encrypt( string $data ): string { |
| 30 |
$nonce = random_bytes( SODIUM_CRYPTO_SECRETBOX_NONCEBYTES ); |
| 31 |
return base64_encode( $nonce . sodium_crypto_secretbox( $data, $nonce, $this->get_key() ) ); // use value from wp-config.php AUTH_KEY as key. |
| 32 |
} |
| 33 |
|
| 34 |
/** |
| 35 |
* Decrypts a given string. |
| 36 |
* |
| 37 |
* @param string $encryptedData |
| 38 |
* @throws \SodiumException |
| 39 |
*/ |
| 40 |
public function decrypt( string $encryptedData ): string { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase |
| 41 |
$data = base64_decode( $encryptedData );// phpcs:ignore WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase |
| 42 |
$nonce = mb_substr( $data, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, '8bit' ); |
| 43 |
$value = mb_substr( $data, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, null, '8bit' ); |
| 44 |
$result = sodium_crypto_secretbox_open( $value, $nonce, $this->get_key() ); |
| 45 |
return empty( $result ) ? '' : $result; |
| 46 |
} |
| 47 |
} |
| 48 |
|