首页 > 解决方案 > 如何捕获 sodium_crypto_box 的异常

问题描述

我正在尝试查看消息是否在中间损坏,我应该能够收到错误,但我看到的只是一个白页。

<?php 
$keypair = hex2bin('66b70b4e93416f8a7a82a40a856fe9884fd7a6e5018837c5421f507307026b40b2c8fbaf820ee38198af1dcf23143ec7ae21da1c785f58d1053940b9f317180e');
$encrypted_text = hex2bin('de261df126463f57b6c38bf42b69252b2f9382267b51e137e20e27ace37c5853279b00c95536cc9a44945146376c5d94355ae0bab5c1eb0ceb9669002ee5dd13e7aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa');
$decrypted_text = sodium_crypto_box_seal_open($encrypted_text, $keypair);
echo $decrypted_text;
?>

正如你所看到的,在 $encrypted_text 中最后有 aaaaaaaaaaaaaa 我应该得到一个错误但没有错误。

标签: phplibsodium

解决方案


Libsodium 函数是低级的。要么使用任何包装器包以方便使用,要么自己创建一个:

interface Decryptor
{
    public function decrypt(string $input): string;
}

final class LibsodiumDecryptor implements Decryptor
{
    private $keyPair;

    public function __construct(string $keyPair)
    {
        $this->keyPair = hex2bin($keyPair);
    }

    public function decrypt(string $input): string
    {
        $decrypted = sodium_crypto_box_seal_open(hex2bin($input), $this->keyPair);

        if (empty($decrypted)) {
            throw new \RuntimeException('Encryption failed');
        }

        return $decrypted;
    }
}

$crypto = new LibsodiumDecryptor('66b70b4e93416f8a7a82a40a856…');

echo $crypto->decrypt('de261df126463f57b6aaaaaaaaaaa…');

推荐阅读