J. Doe J. Doe -3 years ago 125
Python Question

AES encryption in python invalid output

I am writing a secure chat program in which uses AES-256 bit encryption, yesterday I was testing out different methods in AES, where the following worked, my program will allow the user to set the encryption key and the program will add or subtract however many characters are needed to have a 32 byte key. Now when I saved the following code yesterday it worked, however, today when I run through the terminal I get this invalid output, but when I run the program from yesterday, It gives me the correct output!! Anyone who would be able to help, that would be great

>>> import Crypto
>>> from Crypto.Cipher import AES
>>> iv = 'xxxxxxxxxxxxxxxx'
>>> key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
>>> cipher = AES.new(key, AES.MODE_CFB, iv)
>>> cipher.encrypt('Hello')
'c\x0f\x81\xc4\xde'
>>> cipher.decrypt('c\x0f\x81\xc4\xde')
'\x88\xd4;YR'

Answer Source

This is because reusing the AES state and the AES state was now mutated. You need to create a new state:

Python 3.5.3 (default, Jan 19 2017, 14:11:04) 
>>> from Crypto.Cipher import AES
>>> iv = 'xxxxxxxxxxxxxxxx'
>>> iv = b'xxxxxxxxxxxxxxxx'
>>> key = b'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
>>> cipher = AES.new(key, AES.MODE_CFB, iv)
>>> cipher.encrypt('Hello')
b'c\x0f\x81\xc4\xde'
>>> cipher.decrypt(b'c\x0f\x81\xc4\xde')
b'\x88\xd4;YR'

Do not reuse the state, but create a new one freshly initialized from the IV.

>>> cipher = AES.new(key, AES.MODE_CFB, iv)
>>> cipher.decrypt(b'c\x0f\x81\xc4\xde')
b'Hello'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download