6

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
Pankhuri Agarwal
  • 764
  • 3
  • 23

1 Answers1

5

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.

Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263
  • I don't understand the logic in this. Consider the class `MyClass` with the methods `double(self, number)` and `half(self, number)`, which double the number and half the number respectively. `half` is the inverse of `double`, so you could think of it as encryption/decryption. `cipher = MyClass()`; `cipher.half(cipher.double(3))` does return `3` – Eric Jin May 31 '19 at 22:07
  • The operations double and half don't have any state of their own. Check [CBC mode](https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher_Block_Chaining_(CBC)), it propagates the ciphertext to be used to parameterize the encryption / decryption of the next block. The first block is parameterized with the IV. – Maarten Bodewes Jun 01 '19 at 22:35
  • Still, they are the same class with the same attributes and methods, just different instance names. – Eric Jin Jun 01 '19 at 23:19