| 1 |
<?php |
| 2 |
|
| 3 |
namespace IvyForms\Services\Payment; |
| 4 |
|
| 5 |
use RuntimeException; |
| 6 |
|
| 7 |
/** |
| 8 |
* Encrypts/decrypts sensitive tokens at rest in WordPress options. |
| 9 |
*/ |
| 10 |
class TokenEncryptionService |
| 11 |
{ |
| 12 |
private const CIPHER = 'AES-256-CBC'; |
| 13 |
|
| 14 |
/** |
| 15 |
* @throws RuntimeException When OpenSSL cannot encrypt the token. |
| 16 |
*/ |
| 17 |
public function encrypt(string $plainText): string |
| 18 |
{ |
| 19 |
if ($plainText === '') { |
| 20 |
return ''; |
| 21 |
} |
| 22 |
|
| 23 |
$key = $this->getKey(); |
| 24 |
$ivLength = openssl_cipher_iv_length(self::CIPHER); |
| 25 |
$iv = openssl_random_pseudo_bytes($ivLength); |
| 26 |
$encrypted = openssl_encrypt($plainText, self::CIPHER, $key, OPENSSL_RAW_DATA, $iv); |
| 27 |
|
| 28 |
if ($encrypted === false) { |
| 29 |
throw new RuntimeException('Unable to encrypt payment token.'); |
| 30 |
} |
| 31 |
|
| 32 |
return base64_encode($iv . $encrypted); |
| 33 |
} |
| 34 |
|
| 35 |
public function decrypt(string $cipherText): string |
| 36 |
{ |
| 37 |
if ($cipherText === '') { |
| 38 |
return ''; |
| 39 |
} |
| 40 |
|
| 41 |
$decoded = base64_decode($cipherText, true); |
| 42 |
if ($decoded === false) { |
| 43 |
return ''; |
| 44 |
} |
| 45 |
|
| 46 |
$ivLength = openssl_cipher_iv_length(self::CIPHER); |
| 47 |
$iv = substr($decoded, 0, $ivLength); |
| 48 |
$encrypted = substr($decoded, $ivLength); |
| 49 |
$plain = openssl_decrypt($encrypted, self::CIPHER, $this->getKey(), OPENSSL_RAW_DATA, $iv); |
| 50 |
|
| 51 |
return $plain !== false ? $plain : ''; |
| 52 |
} |
| 53 |
|
| 54 |
private function getKey(): string |
| 55 |
{ |
| 56 |
return hash('sha256', wp_salt('auth'), true); |
| 57 |
} |
| 58 |
} |
| 59 |
|