使用3DES和CBC破坏了我的加密数据的前8个字节 [英] First 8 byes of my encrypted data corrupting using 3DES and CBC
问题描述
我在应用程序中使用PyCrypto加密数据,但是由于某种原因,无论我做什么,前8个字节(对应于第一个块)都会损坏。
I'm using PyCrypto in an application to encrypt data, but for some reason the first 8 bytes (corresponding to the first block) are coming through corrupt no matter what I do.
>>> from Crypto.Cipher import DES3
>>> from Crypto import Random
>>> iv = Random.new().read(DES3.block_size)
>>> key = Random.new().read(DES3.key_size[-1])
>>> des3 = DES3.new(key, DES3.MODE_CBC, iv)
>>> des3.decrypt(des3.encrypt('12345678abcdefgh12345678'))
't\x1b\x0f\xcbD\x15M\xababcdefgh12345678'
我已经读过这是IV损坏的迹象,但是那些消息人士还说,使用CBC以外的模式会导致整个消息损坏。情况并非如此:
I've read that that's a sign that the IV is corrupt, but those sources also say that using a mode other than CBC would result in the entire message corrupting. That isn't the case:
>>> des3 = DES3.new(key, DES3.MODE_CFB, iv)
>>> des3.decrypt(des3.encrypt('12345678abcdefgh12345678'))
'\xe1\x85\xae,\xf1m\x83\x9cabcdefgh12345678'
我也可以排除密码的原因:
I can also rule out the cipher as the cause:
>>> from Crypto.Cipher import AES
>>> from Crypto import Random
>>> iv = Random.new().read(AES.block_size)
>>> key = Random.new().read(AES.key_size[-1])
>>> aes = AES.new(key, AES.MODE_CBC, iv)
>>> aes.decrypt(aes.encrypt('12345678abcdefgh12345678abcdefgh'))
'\xa7l\x00]\x1cW\xec\xd0\x04\x06\xba&\x1663\xd712345678abcdefgh'
请注意,在此示例中,前16个字节已损坏,这与AES'块大小相对应。
Note that in this example the first 16 bytes are corrupt, which corresponds to AES' block size.
推荐答案
您必须在解密之前重置IV向量。尝试以下代码:
You have to reset IV vector before decryption. Try this code:
>>> from Crypto.Cipher import DES3
>>> from Crypto import Random
>>> iv = Random.new().read(DES3.block_size)
>>> key = Random.new().read(DES3.key_size[-1])
>>> des3enc = DES3.new(key, DES3.MODE_CBC, iv)
>>> des3dec = DES3.new(key, DES3.MODE_CBC, iv)
>>> des3dec.decrypt(des3enc.encrypt('12345678abcdefgh12345678'))
加密/解密后,向量向量正在更改每个块。您使用了DES3类的同一实例来加密和解密消息,因此解密时使用的IV错误。
IV vector is changing after encryption / decryption each block. You used the same instance of DES3 class for encrypting and decrypting the message, therefore you had incorrect IV for decryption.
希望上面的代码有效-我没有测试它。
Hope above code works - I didn't test it.
有关CBC模式的更多信息: http:// en .wikipedia.org / wiki / Block_cipher_mode_of_operation
More about CBC mode: http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation
这篇关于使用3DES和CBC破坏了我的加密数据的前8个字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!