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);
相关推荐
咚咚王者2 分钟前
人工智能之编程进阶 Python高级:第十一章 过渡项目
开发语言·人工智能·python
大G的笔记本6 分钟前
Java常见设计模式面试题(高频)
java·开发语言·设计模式
笃行客从不躺平30 分钟前
线程池原理复习
java·开发语言
A尘埃44 分钟前
LLM大模型评估攻略
开发语言·python
littlepeanut.top1 小时前
C++中将FlatBuffers序列化为JSON
开发语言·c++·json·flatbuffers
一念一花一世界1 小时前
Arbess从初级到进阶(7) - 使用Arbess+GitLab实现PHP项目自动化部署
ci/cd·gitlab·php·arbess
一晌小贪欢1 小时前
【Python办公】处理 CSV和Excel 文件操作指南
开发语言·python·excel·excel操作·python办公·csv操作
Android系统攻城狮1 小时前
Android内核进阶之获取DMA地址snd_pcm_sgbuf_get_addr:用法实例(九十一)
android·pcm·android内核·音频进阶·pcm硬件参数
清风与日月1 小时前
c# 集成激光雷达(以思岚A1为例)
开发语言·c#
是苏浙1 小时前
零基础入门C语言之贪吃蛇的实现
c语言·开发语言·数据结构