我正在尝试用C加密文本,并在AES中使用EAX模式用python解密它。我使用Bouncy Castle作为C中的EAX,使用AES作为Python。你知道吗
我能够成功地用C#和Python加密和解密文本,但是我注意到,当C#加密文本时,输出比Python加密文本时要长得多。你知道吗
不确定它是否相关,但我正在通过服务器将它从C#发送到Python,并且我确认所有内容都按它应该的方式发送。客户端运行的是Android仿真器,而服务器运行的是windows10。你知道吗
我用来测试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#中的默认编码是UTF-16LE,它应该为您提供两个字节的明文,因此提供两个字节的密文。然而,在C#/Bouncy Castle码中,返回的密文在末尾包含16字节的身份验证标记。很明显你少了一个字节,17个字节短了一个字节。所以密文的传输失败了。当然,在这种情况下,验证标签也会失败。你知道吗
在Python中,密文是一个字节,身份验证标记是16个字节。这对于单个字节的输入是正确的。您的编码不在给定的代码片段中,但我假定它是UTF-8中的一个字节。你知道吗
确保您的C代码也使用UTF-8,并确保密文正确传输。确保在需要通过文本接口传输的地方使用base64,并且不要跳过零值字节。最后,如果您使用随机nonce,请确保使用密文传输它(通常带有前缀)。毕竟你应该没事。你知道吗
相关问题 更多 >
编程相关推荐