我试图用C#加密文本,并在python中使用AES中的EAX对其进行解密。在C#中,我使用的是弹跳城堡,在Python中使用的是AES。
我能够在C#和Python中成功地加密和解密,但是我注意到,当C#对文本进行加密时,输出要比对文本加密时长得多。
不确定它是否相关,但我将通过服务器将其从C#发送到Python,并且确认所有的内容都按应有的方式发送。当服务器运行Windows 10时,客户机正在运行Android仿真器。
我用来测试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和nonce都是一致的16字节。
示例C#输出: 34 2D 0A E9 8A 37 AC 67 0E 95 DB 91 D7 8C E5 4E 9F
Python输出示例: DD
发布于 2019-04-16 13:36:21
C#中的默认编码是UTF-16LE,它应该为您提供两个字节的明文,从而给您两个字节的密文。但是,在C# /bouny城堡代码中,返回的密文在末尾包含16个字节的身份验证标记。很明显,你少了一个字节,17个字节少了一个字节。所以密文的传输在某个地方失败了。当然,在这种情况下,身份验证标记的验证也将失败。
在Python中,密文是一个字节,身份验证标记是16个字节。对于一个字节的输入,这是正确的。您的编码不是在给定的代码片段中,但我假设它是UTF-8中的一个字节。
确保您也对您的C#代码使用UTF-8,并确保正确传输密文。确保在需要通过文本接口进行传输的地方使用基64,并且不要跳过零值字节。最后,如果你使用一个随机的现在,确保你传输它与密文(通常是前缀)。毕竟你应该没事的。
https://stackoverflow.com/questions/55707650
复制相似问题