| 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 |
require_once ABSPATH . WPINC . '/sodium_compat/autoload.php'; |
| 14 |
Log::debug_log(class_exists('ParagonIE_Sodium_Compat') ? 'Found' : 'ParagonIE\Sodium\Compat not found'); |
| 15 |
} |
| 16 |
} |
| 17 |
|
| 18 |
/** |
| 19 |
* Wrap crypto_aead_*_encrypt() in a drop-dead-simple encryption interface |
| 20 |
* |
| 21 |
* @link https://paragonie.com/b/kIqqEWlp3VUOpRD7 |
| 22 |
* @param string $message |
| 23 |
* @param string $key |
| 24 |
* @return string |
| 25 |
*/ |
| 26 |
public function compatEncrypt($message, $key) |
| 27 |
{ |
| 28 |
// cast $message to string |
| 29 |
if (!is_string($message)) { |
| 30 |
$message = strval($message); |
| 31 |
} |
| 32 |
|
| 33 |
$nonce = \random_bytes(24); // NONCE = Number to be used ONCE, for each message |
| 34 |
$encrypted = \ParagonIE_Sodium_Compat::crypto_aead_xchacha20poly1305_ietf_encrypt( |
| 35 |
$message, |
| 36 |
$nonce, |
| 37 |
$nonce, |
| 38 |
$key |
| 39 |
); |
| 40 |
|
| 41 |
return $nonce . $encrypted; |
| 42 |
} |
| 43 |
|
| 44 |
/** |
| 45 |
* Wrap crypto_aead_*_decrypt() in a drop-dead-simple decryption interface |
| 46 |
* |
| 47 |
* @link https://paragonie.com/b/kIqqEWlp3VUOpRD7 |
| 48 |
* @param string $message - Encrypted message |
| 49 |
* @param string $key - Encryption key |
| 50 |
* @return string |
| 51 |
* @throws Exception |
| 52 |
*/ |
| 53 |
public function compatDecrypt($message, $key) |
| 54 |
{ |
| 55 |
$nonce = mb_substr($message, 0, 24, '8bit'); |
| 56 |
$ciphertext = mb_substr($message, 24, null, '8bit'); |
| 57 |
$plaintext = \ParagonIE_Sodium_Compat::crypto_aead_xchacha20poly1305_ietf_decrypt( |
| 58 |
$ciphertext, |
| 59 |
$nonce, |
| 60 |
$nonce, |
| 61 |
$key |
| 62 |
); |
| 63 |
if (!is_string($plaintext)) { |
| 64 |
Log::debug_log('Decryption failed'); |
| 65 |
} |
| 66 |
return $plaintext; |
| 67 |
} |
| 68 |
} |
| 69 |
|