5

below code sample does not return the original text after encrypt/decrypt operation and I am trying to figure it out why

from Crypto.Cipher import AES

text = """This is plain text 
to use.
It should be exqctly 128 characters long to avoid padding and it is split
with new lines as in 
file"""

password = "password........"

block = 32
mode = AES.MODE_CBC

enc = AES.new(password, mode)

encrypted = enc.encrypt(text)

print "ORIGINAL: " + text

print "ENCRYPTED: " + str(encrypted)

print "DECRYPTED: " + str(enc.decrypt(encrypted))

can one tell why first part of the text is malformed ?

1 Answer 1

7

I think, you need to reset the initialisation vector (IV), in order to get the desired result. The easist way might be to create a new AES object for decrypting:

enc = AES.new(password, mode)
encrypted = enc.encrypt(text)
print "ORIGINAL: " + text
print "ENCRYPTED: " + str(encrypted)
dec = AES.new(password, mode)
print "DECRYPTED: " + str(dec.decrypt(encrypted))
Sign up to request clarification or add additional context in comments.

2 Comments

can't you explicitly set and get the IV? Better to get the IV of the encrypter and set the IV for the decrypter.
You can set it in the constructor (third parameter to AES.new). I think the current implementation uses a default IV (not a random one), so it's not strictly necessary to copy it from the encrypter to the decrypter (note, this would have to be done before the encryption!). For security reasons, it would be best to use a different (random) IV for each encryption, but you need to pass it somehow to the decrypter, so it might not be worth the additional effort ... See en.wikipedia.org/wiki/Initialization_vector for more info.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.