项目中使用libsodium扩展

前段时间研究了微信小微商户,地址:https://pay.weixin.qq.com/wiki/doc/api/xiaowei.php?chapter=19_11

其接口操作中需要下载证书针对返回的密文用 AEAD_AES_256_GCM 算法解密

其中用到了 string sodium_crypto_aead_aes256gcm_decrypt ( string $ciphertext , string $ad , string $nonce , string $key ) 这个函数

但是这个函数可能调用的时候会报错,那是因为使用这个函数需要开启 libsodium 扩展才能使用

官方文档上面对该扩展的说明如下:

As of PHP 7.2.0 this extension is bundled with PHP. For older PHP versions this extension is available via PECL.

从php 7.2.0开始,这个扩展与php捆绑在一起。对于旧的PHP版本,此扩展可通过pecl获得。

windows 安装方法

(PHP ≥ 7.2) 直接去 php.ini 开启扩展就行 ,extension=php_sodium.dll 。因为 PHP7.2 版本后 PHP core 中就整合加密库 Libsodium
(PHP < 7.2.0) 需要安装,libsodium PECL 地址 http://pecl.php.net/package/libsodium然后下载 DLL 文件

下载完成后解压,然后

  • 把 php_sodium.dll 文件放到你的php安装目录下的ext目录下(我这运行的是phpStudy安装的php环境)
  • libsodium.dll 文件直接放到PHP安装的根目录
  • 配置下php.ini,开启使用扩展extension=php_sodium.dll
  • 最后重启下php,
  • 查看phpinfo,大功告成

对于PHP 7以下版本windows上我测试了php 5.6,1.0.6 version 能安装但是不能使用 sodium_crypto_aead_aes256gcm_decrypt 函数。

因为5.6上支持的版本为1.0.6,而只有大于1.0.8的版本才支持此函数。

 

Sodium Compat PHP 类库,网上说旧的PHP上可以使用这个类库实现。

Sodium Compat 是用于 Sodium 加密库(libsodium)的纯 PHP 填充,它是 PHP 7.2.0+ 的核心扩展,也可用于 PECL。
这个库 tentativeley 支持PHP 5.2.4 - 7.x(最新版),但官方只支持非 EOL 版本的 PHP。
如果安装了 PHP 扩展,Sodium Compat 将机会性地透明地使用 PHP 扩展而不是我们的实现。
github 地址: https://github.com/paragonie/sodium_compat

实际证明无法实现,因为低于7.1版本的php_openssl,不支持AEAD_AES_256_GCM算法的加密和解密。

所以只能使用7.1以上的PHP版本来解决了。

外文连接:https://paragonie.com/book/pecl-libsodium/read/00-intro.md#installing-libsodium

作者:旧旧的 <393210556@qq.com> 解决问题的方式,就是解决它一次

原文地址:https://www.cnblogs.com/widgetbox/p/10922296.html