【发布时间】:2019-09-06 12:37:03
【问题描述】:
我正在尝试在 C# 中加密文本并在 python 中使用 AES 中的 EAX 模式对其进行解密。我在 C# 中将 Bouncy Castle 用于 EAX,在 Python 中使用 AES。
我能够在 C# 和 Python 中成功地加密和解密,但是我注意到当 C# 加密文本时,输出比 Python 加密时长得多。
不确定它是否相关,但我通过服务器将其从 C# 发送到 Python,并且我确认所有内容都按应有的方式发送。客户端运行 Android 模拟器,而服务器运行 Windows 10。
我用来测试 C# 代码的方法:
const int MAC_LEN = 16
//The Key and Nonce are randomly generated
AeadParameters parameters = new AeadParameters(key, MAC_LEN * 8, nonce);
string EaxTest(string text, byte[] key, AeadParameters parameters)
{
KeyParameter sessKey = new KeyParameter(key);
EaxBlockCipher encCipher = new EAXBlockCipher(new AesEngine());
EaxBlockCipher decCipher = new EAXBlockCipher(new AesEngine());
encCipher.Init(true, parameters);
byte[] input = Encoding.Default.GetBytes(text);
byte[] encData = new byte[encCipher.GetOutputSize(input.Length)];
int outOff = encCipher.ProcessBytes(input, 0, input.Length, encData, 0);
outOff += encCipher.DoFinal(encData, outOff);
decCipher.Init(false, parameters);
byte[] decData = new byte[decCipher.GetOutputSize(outOff)];
int resultLen = decCipher.ProcessBytes(encData, 0, outOff, decData, 0);
resultLen += decCipher.DoFinal(decData, resultLen);
return Encoding.Default.GetString(decData);
}
我用来测试python代码的方法:
def encrypt_text(data, key):
cipher = AES.new(key, AES.MODE_EAX)
nonce = cipher.nonce
cipher_text, mac_tag = cipher.encrypt_and_digest(data)
return [cipher_text, mac_tag, nonce]
def decrypt_text(data, key, mac_tag, nonce):
decrypt = AES.new(key, AES.MODE_EAX, nonce=nonce, mac_len=16)
plaintext = decrypt.decrypt_and_verify(data, mac_tag)
return plaintext
对于字符串“a”的测试,在 C# 中,我始终获得 17 个字节的加密文本,而使用 python,我始终获得 1 个字节的加密文本。 当我尝试在 python 中解密时,我收到此错误 [ValueError: MAC check failed]。 Mac 和 nonce 都是 16 字节。
示例 C# 输出:34 2D 0A E9 8A 37 AC 67 0E 95 DB 91 D7 8C E5 4E 9F
示例 Python 输出:DD
【问题讨论】:
标签: c# python encryption aes bouncycastle