I'm trying my hand at Cryptography using Python2.7. I'm able to encrypt-decrypt a text once. But when I try to encrypt-decrypt multiple times, in a loop, it doesn't give back the original string in variable p. Please have a look at my code, and suggest what can be done. Thanks!
import os, random from Crypto.Cipher import AES from Crypto.Hash import SHA256 '''Encryption''' k = 'mykey' hasher = SHA256.new(k) k = hasher.digest() p = 'enigmaticaura' print p IV = '' lp = len(p) for i in range(16): IV += chr(random.randint(0,0xFF)) if len(p)%16 != 0: p += ' '*(16 - len(p)%16) enc = AES.new(k, AES.MODE_CBC, IV) for i in range(2): p = enc.encrypt(p) print p '''Decryption''' dec = AES.new(k, AES.MODE_CBC, IV) for i in range(2): p = dec.decrypt(p) #p = p[:lp] print p
So, what's the problem with the result?
Your problem description is not helpful. What exactly are you expecting? What exactly are you getting?
The problem is that I'm not able to get the original string p (='enigmaticaura') after decryption. Have also edited the question accordingly.
Please use the checkmark next to the answer to say the question is solved
It worked. Thanks a lot! :) Although, I'm not really sure why it worked. The enc/dec variable was not altered, so redefining them again for the next iteration doesn't make sense. I guess using the .encrypt/.decrypt method was perhaps the reason.
harsh-kolhatkar That's the point - the enc/dec variables are altered, internally. They maintain internal state and can't be reused. By recreating them you are, in effect, resetting them.
got it. thanks :)