You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AES-256-GCM加解密适配API问题求助(.NET+BouncyCastle)

AES-256-GCM加解密本地自测正常,但调用第三方API始终提示“Cannot decrypt message”

对接第三方API需要实现AES-256-GCM加解密逻辑,对方提供了PHP示例代码。我基于.NET框架用BouncyCastle库开发了对应实现,本地自行加解密测试完全正常,但调用API时一直返回“Cannot decrypt message”错误。

已经反复查阅相关文档、调试迭代多版代码,问题仍未解决,贴出当前代码寻求帮助:

.NET加密代码

using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Parameters;
using System.Text;

public static string AesGcmEncrypt(string plainText, byte[] key, byte[] nonce)
{
    var gcmCipher = new GcmBlockCipher(new AesEngine());
    var aeadParams = new AeadParameters(new KeyParameter(key), 128, nonce);
    gcmCipher.Init(true, aeadParams);

    byte[] plainBytes = Encoding.UTF8.GetBytes(plainText);
    byte[] outputBuffer = new byte[gcmCipher.GetOutputSize(plainBytes.Length)];
    
    int processedLength = gcmCipher.ProcessBytes(plainBytes, 0, plainBytes.Length, outputBuffer, 0);
    gcmCipher.DoFinal(outputBuffer, processedLength);

    // 参照PHP示例拼接nonce、密文、tag
    byte[] combined = nonce.Concat(outputBuffer).ToArray();
    return Convert.ToBase64String(combined);
}

.NET解密代码

public static string AesGcmDecrypt(string encryptedText, byte[] key)
{
    byte[] combinedBytes = Convert.FromBase64String(encryptedText);
    // 取前12字节作为nonce(GCM标准推荐长度)
    byte[] nonce = combinedBytes.Take(12).ToArray();
    byte[] cipherWithTag = combinedBytes.Skip(12).ToArray();

    var gcmCipher = new GcmBlockCipher(new AesEngine());
    var aeadParams = new AeadParameters(new KeyParameter(key), 128, nonce);
    gcmCipher.Init(false, aeadParams);

    byte[] plainBuffer = new byte[gcmCipher.GetOutputSize(cipherWithTag.Length)];
    
    int processedLength = gcmCipher.ProcessBytes(cipherWithTag, 0, cipherWithTag.Length, plainBuffer, 0);
    gcmCipher.DoFinal(plainBuffer, processedLength);

    return Encoding.UTF8.GetString(plainBuffer);
}

对方提供的PHP示例代码片段

function encrypt($plaintext, $key, $nonce) {
    $ciphertext = openssl_encrypt($plaintext, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $nonce, $tag);
    return base64_encode($nonce . $ciphertext . $tag);
}

function decrypt($ciphertext, $key) {
    $data = base64_decode($ciphertext);
    $nonce = substr($data, 0, 12);
    $ciphertextPart = substr($data, 12, -16);
    $tag = substr($data, -16);
    return openssl_decrypt($ciphertextPart, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $nonce, $tag);
}

本地测试时,用我的.NET代码加密后再解密能得到原文本,但和第三方API交互就失败,有没有大佬能看出哪里存在差异?

内容的提问来源于stack exchange,提问作者Basje313

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 03:21:57