php AEAD_AES_256_GCM算法 解密

基于 商家转账批次回调通知 ,使用的是 AEAD_AES_256_GCM算法 解密

使用 php7.1以上 开启扩展 Sodium,方可使用

php 复制代码
const AUTH_TAG_LENGTH_BYTE = 16;
/*
*$associatedData 附加数据 对应接收参数 associated_data
*$nonceStr 对应接收参数 nonce
*$ciphertext 需要解析的内容 ciphertext
*$aesKey 商户v3 设置的秘钥
*/
private function decryptToString($associatedData, $nonceStr, $ciphertext, $aesKey = '')
    {
        if (empty($aesKey)) {
            $aesKey = $this->mch_key;
        }
        $ciphertext = base64_decode($ciphertext);
        if (strlen($ciphertext) <= self::AUTH_TAG_LENGTH_BYTE) {
            return false;
        }

        // ext-sodium (default installed on >= PHP 7.2)
        if (function_exists('sodium_crypto_aead_aes256gcm_is_available') &&
            sodium_crypto_aead_aes256gcm_is_available()) {
            return sodium_crypto_aead_aes256gcm_decrypt($ciphertext, $associatedData, $nonceStr, $aesKey);
        }

        // ext-libsodium (need install libsodium-php 1.x via pecl)
        if (function_exists('Sodiumcrypto_aead_aes256gcm_is_available') &&
            Sodiumcrypto_aead_aes256gcm_is_available()) {
            return Sodiumcrypto_aead_aes256gcm_decrypt($ciphertext, $associatedData, $nonceStr, $aesKey);
        }

        // openssl (PHP >= 7.1 support AEAD)
        if (PHP_VERSION_ID >= 70100 && in_array('aes-256-gcm', openssl_get_cipher_methods())) {
            $ctext = substr($ciphertext, 0, -self::AUTH_TAG_LENGTH_BYTE);
            $authTag = substr($ciphertext, -self::AUTH_TAG_LENGTH_BYTE);

            return openssl_decrypt($ctext, 'aes-256-gcm', $aesKey, OPENSSL_RAW_DATA, $nonceStr,
                $authTag, $associatedData);
        }

        throw new RuntimeException('AEAD_AES_256_GCM需要PHP 7.1以上或者安装libsodium-php');
    }

调用方法

php 复制代码
// 解密
$decrypted = openssl_decrypt($ciphertext, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $iv, $tag, $aad);
相关推荐
每天一个秃顶小技巧12 分钟前
02.Golang 切片(slice)源码分析(一、定义与基础操作实现)
开发语言·后端·python·golang
serve the people2 小时前
解决osx-arm64平台上conda默认源没有提供 python=3.7 的官方编译版本的问题
开发语言·python·conda
柒七爱吃麻辣烫2 小时前
在Linux中安装JDK并且搭建Java环境
java·linux·开发语言
极小狐2 小时前
如何构建容器镜像并将其推送到极狐GitLab容器镜像库?
开发语言·数据库·机器学习·gitlab·ruby
多多*3 小时前
Java反射 八股版
java·开发语言·hive·python·sql·log4j·mybatis
正在走向自律3 小时前
从0到1:Python机器学习实战全攻略(8/10)
开发语言·python·机器学习
FY_20183 小时前
键盘输出希腊字符方法
开发语言
西西弗Sisyphus3 小时前
Python 处理图像并生成 JSONL 元数据文件 - 灵活text版本
开发语言·python
q567315234 小时前
Go语言多线程爬虫与代理IP反爬
开发语言·爬虫·tcp/ip·golang
Chandler244 小时前
Go语言即时通讯系统 开发日志day1
开发语言·后端·golang