php - 如何捕获 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 我应该得到一个错误但没有错误。
解决方案
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…');
推荐阅读
- java - Spring-Boot在支持String Array(String [])数据类型的内存数据库中兼容
- clang - 使用 OpenMP 的 Clang 编译的 Python 扩展中的未定义符号
- css - 从 Angular 7 更新后,Angular 9 和样式加载器停止工作
- javascript - 仅在打开时加载 Bootstrap 模态内容
- c# - 如何修复 ElasticSearch 索引中无意重复的值?
- javascript - 如果使用多个导入而不是一个命名导入,是否会产生性能成本
- android - 以编程方式将 boxBackgroundMode 设置为 TextInputLayout
- c# - 我想为我的网站上传个人资料,但 #FileUpload2 行中有错误
- excel - 寻找最后一行并让它填充另一列
- c# - 迭代数组并将强类型添加到列表