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);
相关推荐
Main. 24几秒前
从0到1学习Qt -- Qt3D入门
开发语言·qt·学习
接着奏乐接着舞。1 分钟前
Go 一小时上手指南:从零到运行第一个程序
开发语言·后端·golang
三少爷的鞋2 分钟前
架构避坑:为什么 UseCase 不该启动协程,也不该切线程?
android
飞机和胖和黄3 分钟前
王道C语言第一周作业
c语言·开发语言
lly2024063 分钟前
SQLite 安装指南
开发语言
星火开发设计6 分钟前
C++ deque 全面解析与实战指南
java·开发语言·数据结构·c++·学习·知识
全栈小59 分钟前
【PHP】如何将ThinkPHP 5部署到windows服务器的IIS里,和PHP版本又是一个怎么样的关系,三分钟教程搞定部署
服务器·windows·php
JaguarJack10 分钟前
2026 年 PHP 8.4 依然重要:跳到 8.5 之前你该掌握的特性
后端·php·服务端
ID_1800790547312 分钟前
除了Python,还有哪些语言可以解析淘宝商品详情API返回的JSON数据?
开发语言·python·json
BingoGo12 分钟前
2026 年 PHP 8.4 依然重要:跳到 8.5 之前你该掌握的特性
后端·php