I am having a problem storing a string encrypted, then b64 encoded in a text file.
The code to encrypt is
from base64 import b64encode, b64decode # import library for B64
from Crypto.Cipher import AES
import datetime
d = datetime.date.today()
shortd = d.strftime("%y%m%d")
docNum = raw_input("Enter Doc Number: ")
#Doc num is always 20 characters,
obj = AES.new('ThisIsA16digitPs', AES.MODE_CBC, 'This is an IV456')
ciphertext = obj.encrypt(shortd+docNum+"000000") #Zeroes for filler
lognum = b64encode(ciphertext)
f = open("e:\log.txt", "a")
f.write(str(lognum) + "\n")
f.close()
The file shows the following text:
uTfZKAuVYbZJM28Tbcv3OBHvDn8QBKm1Nbb0wjcq9rE=
wCeIeyDBShmbsjM1yIpzEPdijAe4o12J4FAhigDotCU=
wCeIeyDBShmbsjM1yIpzEPHZ9fsBlE+svpzBxwcunoU=
wCeIeyDBShmbsjM1yIpzEODr4Ko91q0lsSnlMSuUlJo=
As I have 4 numbers in there.
The code to decrypt is
from base64 import b64encode, b64decode # import library for B64
from Crypto.Cipher import AES # Import AES encryption module
obj2 = AES.new('ThisIsA16digitPs', AES.MODE_CBC, 'This is an IV456')
with open('e:\\log.txt', "r") as logfile:
for line in logfile:
docstring2 = obj2.decrypt(b64decode(line))
print docstring2
if not line:
logfile.close()
break
But when I run it, the returned result is
15071110000000000000000001000000
t²W;\è¥dèä»Q.ó·0000000002000000
’?ÕC©û™±1ófì±#0000000003000000
”„¬¿Ì¼ïÂѾa*›ƒ0000000004000000
The first line is correct. The others should loook just like it.
15071110000000000000000001000000
15071120000000000000000002000000
15071120000000000000000003000000
15071120000000000000000004000000
So, what am I doing wrong? I'm new at python, and cannot figure this one out.
Edit: I am on Python 2.7.10 on win32.
At decryption time, you initialize the CBC cipher once and then decrypt all rows with it, one after the other.
I believe you do not do that at encryption time. In other words, you might be initializing the CBC cipher four times, right before encrypting each line.
The fix is to move obj2
creation inside the first loop in the decryption code.
On a separate note, the IV for CBC should be random, not take a fixed value.