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

.NET 4.8下BouncyCastle实现AES GCM解密报MAC校验错误求助

AES GCM解密在.NET 4.8+BouncyCastle中MAC校验失败的排查与修复

问题出在.NET原生AesGcm与BouncyCastleGcmBlockCipher的参数处理逻辑差异上:
-.NET的AesGcm.Decrypt方法允许分开传递密文和标签,但BouncyCastle的GCM实现要求将密文与标签拼接成同一个字节数组作为输入数据——它会在解密流程末尾自动读取标签并完成MAC校验。

你的.NET 4.8分支代码仅传入了密文,没有将标签纳入处理流程,导致BouncyCastle无法获取校验所需的标签数据,最终抛出mac check in GCM failed异常。

修复后的代码如下:

#if NET48
    var cipher = new GcmBlockCipher(new AesEngine());
    cipher.Init(false, new AeadParameters(new KeyParameter(key), tag.Length * 8, iv, aad));
    
    // 合并密文与标签,匹配BouncyCastle GCM的输入要求
    byte[] ciphertextWithTag = new byte[encrypt.Length + tag.Length];
    Buffer.BlockCopy(encrypt, 0, ciphertextWithTag, 0, encrypt.Length);
    Buffer.BlockCopy(tag, 0, ciphertextWithTag, encrypt.Length, tag.Length);
    
    plaintextBytes = new byte[cipher.GetOutputSize(ciphertextWithTag.Length)];
    int len = cipher.ProcessBytes(ciphertextWithTag, 0, ciphertextWithTag.Length, plaintextBytes, 0);
    cipher.DoFinal(plaintextBytes, len);
#else
    using (var decryptor = new AesGcm(key))
        decryptor.Decrypt(iv, encrypt, tag, plaintextBytes, aad);
#endif

额外验证点:

  • 确保IV长度为12字节(96位),这是AES GCM的推荐标准长度,两端实现均兼容该长度
  • 确认密钥长度符合AES要求(128/192/256位),且两端使用的密钥完全一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 12:10:18