pycrypto: what am I doing wrong?

Chris Angelico rosuav at gmail.com
Thu Oct 24 03:07:16 EDT 2013


On Thu, Oct 24, 2013 at 4:22 PM, Paul Pittlerson <menkomigen6 at gmail.com> wrote:
> msg = cipher.encrypt(txt)
>
>>>> '|s\x08\xf2\x12\xde\x8cD\xe7u*'
>
> msg = cipher.encrypt(txt)
>
>>>> '\xa1\xed7\xb8h<l\x7f\xd7\xba\xed'
>
> # etc

Is this strictly the code you're using? AES is a stream cipher; what
you've effectively done is encrypt the text twice, once as a follow-on
message from the other. To decrypt the second, you'll need to include
the first - or treat it as a stream, and decrypt piece by piece.
Untested code:

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

# Shorter version of your key hashing:
key = hashlib.sha256("my key").digest()

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

msg1 = cipher.encrypt(txt)
msg2 = cipher.encrypt(txt)
# You may need to reset cipher here, I'm not sure.
# cipher = AES.new(key, AES.MODE_CFB, iv)
cipher.decrypt(iv) # Initialize the decrypter with the init vector
print(cipher.decrypt(msg1))
print(cipher.decrypt(msg2))



I don't have pycrypto to test with, but running the same code with
Pike's Crypto module does what I expect here.

ChrisA



More information about the Python-list mailing list