0

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.

PaulP
  • 48
  • 6

2 Answers2

1

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.

  • Thank you, this did it! The lines are added one at a time as part of another process, but they are pulled out all at once (and then filtered). – PaulP Jul 12 '15 at 20:20
0

I think your problem is that you forgot to use binary mode when storing and retrieving a file.

With b64 it shouldn't be a problem, but something obviously is.

Try using ab and rb, just in case. Maybe Python made a mess with new lines. If you are using Python 3, I wouldn't be surprised. I am not hopeful though.

Anyway, try printing repr(line) and len(line) so that you have something to compare to.

Dalen
  • 4,128
  • 1
  • 17
  • 35