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);
相关推荐
好的佩奇4 分钟前
Dart 之增强枚举
android·flutter·dart
starzy199016 分钟前
Scala循环与判断:一切皆表达式的控制流
开发语言·人工智能·scala
starzy199031 分钟前
Scala类和对象:从构造器到样例类的完整指南
开发语言·后端·scala
梦影_38 分钟前
MySQL进阶教程(五)—— SQL调优(下)
android·大数据·数据库·后端·sql·mysql·database
niucloud-admin42 分钟前
NIUCLOUD PHP SAAS上门家政使用文档--服务订单:订单列表
开发语言·php
一枕槐安48744 分钟前
大模型限流、重试、超时处理:API 调用健壮性方案
linux·服务器·php·大模型api·指数退避·限流控制·超时预算
怪我冷i1 小时前
Rust 的impl语法详解
开发语言·后端·rust
李纲明1 小时前
WordPress 白屏或提示「出现了严重错误」:先开 WP_DEBUG 抓致命错误,再二分插件与主题
运维·php·debug·wordpress·白屏·插件冲突·devdiy
qq_406981032 小时前
c++的decltype是什么
开发语言·c++
坤坤子吖2 小时前
算法学习——单调队列
开发语言·c++·笔记·学习·算法