pycrypto: what am I doing wrong?

Paul Pittlerson menkomigen6 at gmail.com
Thu Oct 24 01:22:38 EDT 2013


I seem to have misunderstood something about the way Crypto.Cipher is supposed to work, because I'm getting unexpected results, here is my code..

import hashlib
from Crypto.Cipher import AES
from Crypto import Random

h = hashlib.new('sha256')
h.update('my key')
key = h.digest()

iv = Random.new().read(AES.block_size)
cipher = AES.new(key, AES.MODE_CFB, iv)
txt = 'hello world'

# This is the part where I'm confused, because it seems like encrypt will output a different result every time, so how can I decrypt it?

msg = cipher.encrypt(txt)

>>> '|s\x08\xf2\x12\xde\x8cD\xe7u*'

msg = cipher.encrypt(txt)

>>> '\xa1\xed7\xb8h<l\x7f\xd7\xba\xed'

# etc
# it works like I would expect the first time when decrypting, if I follow the example from pycrypto docs:

msg = iv + cipher.encrypt(txt)
cipher.decrypt(iv + msg)

>>> '\x0b\xd9\x9f0\xd1\xb9E\x81;\x8a\xd4\xff\xdb\xd4\x83\x84\xbd$=\xf3\xaf at a8t\xd8Bz<\xce\xe26hello world'

# But it does not work subsequently:

msg = iv + cipher.encrypt(txt)
cipher.decrypt(iv+msg)

>>> '\xfb\xa1\xa8\x9e"L<\x10Rg\xb5f^\x8a\x17\xfd\xbd$=\xf3\xaf at a8t\xd8Bz<\xce\xe26\xde\xc6cD\xdal\'\xf3@(\xa6'

What am I doing wrong?



More information about the Python-list mailing list