我正在尝试使用C#加密文本并使用AES中的EAX模式在python中解密文本。我在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检查失败]。Mac和随机数始终为16字节。
示例C#输出:34 2D 0A E9 8A 37 AC 67 0E 95 DB 91 D7 8C E5 4E 9F
示例Python输出:DD
C#中的默认编码为UTF-16LE,它应为您提供两个字节的纯文本,并因此为您提供两个字节的密文。但是,在C#/ Bouncy Castle代码中,返回的密文末尾包含16个字节的身份验证标签。显然,您缺少一个字节,而17个字节短了一个字节。因此密文的传输在某处失败。当然,在这种情况下,验证标签的验证也将失败。
在Python中,密文为1个字节,而身份验证标签为16个字节。这对于输入的单个字节是正确的。您的编码不在给定的代码片段中,但我想它是UTF-8中的一个字节。
确保对C#代码也使用UTF-8,并确保正确传输密文。确保使用要求通过文本接口进行传输的base 64,并且不要跳过零值字节。最后,如果您使用随机随机数,请确保使用密文(通常带前缀)传输它。毕竟您应该没事。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句