| 1 |
<?php |
| 2 |
|
| 3 |
namespace Bitcode\BitForm\Core\Cryptography; |
| 4 |
|
| 5 |
use BitCode\BitForm\Core\Util\Log; |
| 6 |
use Exception; |
| 7 |
|
| 8 |
class SodiumCompat |
| 9 |
{ |
| 10 |
public function __construct() |
| 11 |
{ |
| 12 |
if (class_exists('ParagonIE_Sodium_Compat')) { |
| 13 |
return; |
| 14 |
} |
| 15 |
|
| 16 |
$autoloader = ABSPATH . WPINC . '/sodium_compat/autoload.php'; |
| 17 |
if (!is_readable($autoloader)) { |
| 18 |
Log::debug_log('WordPress sodium_compat autoloader not readable at ' . $autoloader); |
| 19 |
|
| 20 |
return; |
| 21 |
} |
| 22 |
|
| 23 |
require_once $autoloader; |
| 24 |
} |
| 25 |
|
| 26 |
/** |
| 27 |
* Wrap crypto_aead_*_encrypt() in a drop-dead-simple encryption interface |
| 28 |
* |
| 29 |
* @link https://paragonie.com/b/kIqqEWlp3VUOpRD7 |
| 30 |
* @param string $message |
| 31 |
* @param string $key |
| 32 |
* @return string |
| 33 |
*/ |
| 34 |
public function compatEncrypt($message, $key) |
| 35 |
{ |
| 36 |
// cast $message to string |
| 37 |
if (!is_string($message)) { |
| 38 |
$message = strval($message); |
| 39 |
} |
| 40 |
|
| 41 |
$nonce = \random_bytes(24); // NONCE = Number to be used ONCE, for each message |
| 42 |
$encrypted = \ParagonIE_Sodium_Compat::crypto_aead_xchacha20poly1305_ietf_encrypt( |
| 43 |
$message, |
| 44 |
$nonce, |
| 45 |
$nonce, |
| 46 |
$key |
| 47 |
); |
| 48 |
|
| 49 |
return $nonce . $encrypted; |
| 50 |
} |
| 51 |
|
| 52 |
/** |
| 53 |
* Wrap crypto_aead_*_decrypt() in a drop-dead-simple decryption interface |
| 54 |
* |
| 55 |
* @link https://paragonie.com/b/kIqqEWlp3VUOpRD7 |
| 56 |
* @param string $message - Encrypted message |
| 57 |
* @param string $key - Encryption key |
| 58 |
* @return string |
| 59 |
* @throws Exception |
| 60 |
*/ |
| 61 |
public function compatDecrypt($message, $key) |
| 62 |
{ |
| 63 |
$nonce = mb_substr($message, 0, 24, '8bit'); |
| 64 |
$ciphertext = mb_substr($message, 24, null, '8bit'); |
| 65 |
$plaintext = \ParagonIE_Sodium_Compat::crypto_aead_xchacha20poly1305_ietf_decrypt( |
| 66 |
$ciphertext, |
| 67 |
$nonce, |
| 68 |
$nonce, |
| 69 |
$key |
| 70 |
); |
| 71 |
if (!is_string($plaintext)) { |
| 72 |
Log::debug_log('Decryption failed'); |
| 73 |
} |
| 74 |
return $plaintext; |
| 75 |
} |
| 76 |
} |
| 77 |
|