2014-04-29 55 views
0

我期待在一些常见蟒示例代码不加密,设置这样的:Python到Java的加密/解密,确保密码匹配?

encryptor = AES.new(key, AES.MODE_CBC, iv) 
chunksize = 64*1024 

while True: 
    chunk = infile.read(chunksize) 
    if len(chunk) == 0: 
     break 
    elif len(chunk) % 16 != 0: 
     chunk += ' ' * (16 - len(chunk) % 16) 

    outfile.write(encryptor.encrypt(chunk)) 

试图建立Java代码从上述解密输出,我看到不同的初始化密码填充例子:

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); 

或:

Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); 

即使所有的Python片段是相同方式实现。

我希望在这种情况下使用“NoPadding”。任何人都可以解释在这种情况下正确的选择是什么?

谢谢

+0

另请注意,如果您位于文件的末尾,则不能保证读取的返回小于所请求的大小。即使这不可能,你在技术上最终只能读取8个字节,这会被填充,因此额外的空间会在加密的明文中结束。关于填充的选择,如果可以改变python方面,那么你应该使用两侧PKCS5(或PKCS7是相同的)填充。用“''”填充你不能区分一个填充的明文和一个刚好在末尾有空格的明文。 – Perseids

+0

@Perseids我想我明白 - 有很多python示例声称是PKCS5或PKCS7,只是用空格填充。我从规格参考中看到不同的:[http://programmerin.blogspot.com/2011/08/python-padding-with-pkcs7.html],[ftp://ftp.rsasecurity.com/pub/pkcs/ ascii/pkcs-7.asc] – user3203425

+0

[blogspot文章]中的一个(http://programmerin.blogspot.de/2011/08/python-padding-with-pkcs7.html)看起来很好,即使我猜测python密码库应该已经有例程。此外,我建议你使用[HMAC](https://en.wikipedia.org/wiki/Hash-based_message_authentication_code)(encrypt-then-mac)加密后认证你的消息,以防止所谓的[填充oracle攻击](http ://robertheaton.com/2013/07/29/padding-oracle-attack/)(请参阅https://security.stackexchange.com/questions/38942/how-to-protect-against-padding-oracle-attacks) 。 – Perseids

回答

1

的Python代码是填充带有空格(' '),除非我误解的代码(不是一个Python的家伙)。您需要在Java代码中手动填充并使用"AES/CBC/NoPadding"