Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pycrypto : AES Decryption

Why Pycrypto AES decryption gives different output when decrypted with AES object used for encryption and right output when decrypted with AES object used solely for decryption?

from Crypto.Cipher import AES
obj = AES.new('0123456789012345', AES.MODE_CBC, '0123456789012345')
message = '0123456789012345'
ciphertext = obj.encrypt(message)
plaintext = obj.decrypt(ciphertext)
# plaintext here is byte array
obj2 = AES.new('0123456789012345', AES.MODE_CBC, '0123456789012345')
plaintext = obj2.decrypt(ciphertext)
# plaintext here is 0123456789012345
like image 456
Pankhuri Agarwal Avatar asked Apr 04 '17 05:04

Pankhuri Agarwal


Video Answer


1 Answers

According to BlockAlgo#encrypt from which the AES class is derived:

Encrypt data with the key and the parameters set at initialization.

The cipher object is stateful; encryption of a long block of data can be broken up in two or more calls to encrypt(). That is, the statement:

c.encrypt(a) + c.encrypt(b)

is always equivalent to:

c.encrypt(a+b)

That also means that you cannot reuse an object for encrypting or decrypting other data with the same key.

So your problem is actually directly documented in the class.

like image 51
Maarten Bodewes Avatar answered Oct 12 '22 13:10

Maarten Bodewes