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
Disclaimer first: Python isn't exactly my strong point but hey, it's been a while since I answered anything so why not...
I guess your question should have been something like "why doesn't the decryption produce the original input".
For one thing - why? Using the same key isn't really going to make the encryption any better.
And for two - it's not meant to work like that. I'm pretty sure it is to do with the fact that the encrypt and decrypt objects are stateful and cannot be reused. This SO post describes it in more detail.
But, two small changes will make it (sort of) work, in as much as you'll get the original source back.
for i in range(2):
enc = AES.new(k, AES.MODE_CBC, IV) ## move this line inside the loop
p = enc.encrypt(p)
print p
and
for i in range(2):
dec = AES.new(k, AES.MODE_CBC, IV) ## and this line too
p = dec.decrypt(p)
which may, or may not be what you were hoping for.