使用PyCrypto使用32字节初始化向量解密MCRYPT_RIJNDAEL_256 [英] Decrypt MCRYPT_RIJNDAEL_256 with 32-byte initialization vectors with PyCrypto

查看:350
本文介绍了使用PyCrypto使用32字节初始化向量解密MCRYPT_RIJNDAEL_256的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有使用PHP加密的数据,如下所示:

I have data that was encrypted in PHP as follows:

mcrypt_encrypt(MCRYPT_RIJNDAEL_256, SECRET, $data, MCRYPT_MODE_CBC, $iv)

我需要在Python 3应用程序中解密此数据。我正在尝试使用PyCrypto,但我对其他库开放。我希望以下代码能正常工作:

I need to decrypt this data in a Python 3 application. I am trying to use PyCrypto but I am open to other libraries. I expect the following to work:

decryptor = AES.new(key, mode, IV=IV)
plain = decryptor.decrypt(ciphertext)

我的初始化向量是32个字节,并抛出以下异常:

My initialization vector is 32 bytes, and the following exception is thrown:

ValueError: IV must be 16 bytes long

如何设置PyCrypto使用32字节的初始化向量和32字节的块大小?
或者,是否可以使用其他库来解密数据?

How can I set PyCrypto to use a 32 byte initialization vector and 32 byte block size? Alternatively, is there a different library that I can use to decrypt the data?

推荐答案

感谢我的评论实施了合适的解决方案。我在链接重复的问题中修改了 rijndael.py 以接受字节而不是字符串。然后,我按如下所示使用它用32字节的初始化向量解密32字节的块。

Thanks to the comments I implemented a suitable solution. I modified rijndael.py in the linked duplicate question to accept bytes rather than strings. I then use it as follows to decrypt 32-byte blocks with the 32-byte initialization vectors.

from rijndael import rijndael

iv = b'myInitializationVectorfoobarfoob'
key = b'myKeyfoobarfoobarfoobarfoobarfoo'
text = b'myCipherTextFoobarfoobarfoobarfo'

r = rijndael(key, block_size=32)
plaintext = r.decrypt(text)
l = ''.join([chr(a ^ b) for a, b in zip(plaintext.encode('latin-1'), iv)])
print(l)

请注意,仅因为libmcrypt错误,才使用此方法而不是PyCrypto设置数据块大小,从而将初始化矢量大小设置为等于密钥大小。据我了解,AES-Rijndael的数据块大小应始终为128位。

Note that using this rather than PyCrypto is only necessary because libmcrypt incorrectly sets the data block sizes, and thus the initialization vector sizes, to be equal to the key sizes. As far as I understand, data block sizes should always be 128 bits for AES-Rijndael.

这篇关于使用PyCrypto使用32字节初始化向量解密MCRYPT_RIJNDAEL_256的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆