The first 8 bytes of my encrypted data corruption using 3DES and CBC

I use PyCrypto in an application to encrypt data, but for some reason the first 8 bytes (corresponding to the first block) go through the corrupted files 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' 

I read that the sign that IV is corrupted, but these sources also say that using a mode other than CBC will corrupt the entire message. This is not true:

 >>> des3 = DES3.new(key, DES3.MODE_CFB, iv) >>> des3.decrypt(des3.encrypt('12345678abcdefgh12345678')) '\xe1\x85\xae,\xf1m\x83\x9cabcdefgh12345678' 

I can also exclude the cipher as a reason:

 >>> 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' 

Note that in this example, the first 16 bytes are corrupted, which corresponds to the size of the AES block.

+4
source share
1 answer

Before decryption, you must reset vector IV. 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')) 

IV vector changes after encryption / decryption of each block. You used the same instance of the DES3 class to encrypt and decrypt a message, so you had the wrong IV for decryption.

I hope that it works on the code - I have not tested it.

More on CBC mode: http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation

+5
source

Source: https://habr.com/ru/post/1478889/


All Articles