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

C#转Python的AES/GCM-256加密结果不一致问题求助

C#转Python的AES/GCM-256加密结果不一致问题求助

大家好,我最近在把C#中的AES/GCM-256加密函数转换成Python版本,遇到了一个头疼的问题:明明两边用的密钥、IV和明文数据完全一致,但加密后的输出结果就是不一样,希望熟悉这两种语言加密实现的朋友能帮我排查下问题所在。

基础信息

  • 共用输入:
    • 密钥(十六进制字符串):4fda3c622e966e0839441401bbd3b8f191d4267bf5f19b40812a34b212fd3ed9
    • IV(十六进制字符串):4fda3c622e966e0839441401bbd3b8f191d4267bf5f19b40812a34b212fd3ed9
    • 明文测试字符串:"In publishing and graphic design, Lorem ipsum is a"
  • 输出对比:
    • C#生成的Base64加密结果:02Em9Vve6fWtAcVNesIXzagoB327EmskwMZdRippAAaxqAzkp0VeGSjctbaguqA/01CnPHB2PkRDDOxjgZ9pAfu2
    • Python生成的Base64加密结果:HudpKzIov7lNt4UNng+a9P/FLXrzdenwDBT4uFYhIUc3XOS7TpaCzxja8I+zHCdXnvk=

C#实现代码

public static string AesEncrypt(byte[] payload, byte[] key, byte[] iv)
{
    var cipher = new GcmBlockCipher(new AesEngine());
    byte[] baPayload = new byte[0];
    cipher.Init(true, new AeadParameters(new KeyParameter(key), 128, iv, baPayload));
    var cipherBytes = new byte[cipher.GetOutputSize(payload.Length)];
    int len = cipher.ProcessBytes(payload, 0, payload.Length, cipherBytes, 0);
    cipher.DoFinal(cipherBytes, len);
    return Convert.ToBase64String(cipherBytes);
}

// 用于将十六进制字符串转字节数组的辅助函数
public static byte[] StringToByteArray(string hex)
{
    return Enumerable.Range(0, hex.Length)
        .Where(x => x % 2 == 0)
        .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
        .ToArray();
}

Python实现代码

import binascii
from Crypto.Cipher import AES

PASSPHRASE = b'a4b42ed2702cb1b00a14f39a88c719cb04e5e8b29e2479634c990258e327483'

def AES_encrypt(data, iv):
    global PASSPHRASE
    key = binascii.unhexlify(PASSPHRASE)
    cipher = AES.new(key, AES.MODE_GCM, iv)
    x = cipher.encrypt(data)
    return x

我的疑问

我确认了两边的输入数据(密钥、IV、明文)都是完全一致的(注:Python代码里的PASSPHRASE是粘贴时的笔误,实际测试时已经替换成正确的密钥字符串了),但输出结果还是不匹配。目前猜测可能是GCM模式的参数处理(比如标签长度、附加数据)或者字节转换方式有差异,但自己暂时没找到具体问题点,麻烦大家帮忙看看哪里出错了,谢谢!

备注:内容来源于stack exchange,提问作者Amalendu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.23 15:37:26