【问题标题】:How to catch an exception for sodium_crypto_box如何捕获 sodium_crypto_box 的异常
【发布时间】:2019-01-11 07:18:26
【问题描述】:

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

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

如您所见,$encrypted_text 末尾有 aaaaaaaaaaaaaa 我应该得到一个错误但没有错误。

【问题讨论】:

  • 为什么不检查$decrypted_text 是否为空?如果是抛出异常。
  • 成功了,谢谢。
  • “但我所看到的只是一个白页” - 好吧,您并没有在显示的代码中发现异常,如果您稍后在某处不这样做,这将在脚本通过时导致致命错误。再加上 PHP 被不合适的错误报告设置堵住了,你得到的结果是一个空白页。

标签: php libsodium


【解决方案1】:

如果消息无法解密,sodium_crypto_box_seal_open() 返回FALSE

您应该将其输出与FALSE 进行比较,而不是检查它是否为空,因为加密空消息是完全可以的。空消息经过身份验证,如果密钥不正确,将被拒绝。

另外,如果涉及机密,您应该使用 sodium_bin2hex()sodium_hex2bin(),它们旨在避免侧通道

【讨论】:

    【解决方案2】:

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

    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…');
    

    【讨论】:

      猜你喜欢
      • 2017-03-14
      • 2016-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多