0

I have the following code written in python and a few lines in the bottom to debug and execute the code:

class encoder:
    encryptor = False
    IV = 16 * '\x00'
    def __init__(self, password):
            self.encryptor = AES.new(sha256(password).digest(), AES.MODE_CBC, self.IV)

    def encode_file(self, path):
        filesize = os.path.getsize(path)

        with open(path, 'rb') as infile:
            with open((path+"1"), 'wb') as outfile:
                outfile.write(struct.pack('<Q', filesize))
                outfile.write(self.IV)

                while True:
                    chunk = infile.read(64*1024)
                    if len(chunk) == 0:
                        break
                    elif len(chunk) % 16 != 0:
                        chunk += ' ' * (16 - len(chunk) % 16)

                    outfile.write(self.encryptor.encrypt(chunk))
    def decrypt_file(self, in_filename,chunksize=24*1024):
        out_filename = "E:\\digested.txt"

        with open(in_filename, 'rb') as infile:
            origsize = struct.unpack('<Q', infile.read(struct.calcsize('Q')))[0]
            iv = infile.read(16)
            with open(out_filename, 'wb') as outfile:
                chunk = infile.read(chunksize)
                outfile.write(self.encryptor.decrypt(chunk))
                outfile.truncate(origsize)

enc = encoder("password")
enc.encode_file("E:\\txt.txt")
enc.decrypt_file("E:\\txt.txt1")

the code is part of an attempt to encrypt whole folders but I am currently testing the encryption and the decryption of a single file. I left the IV simple and have not salted the hash for comfort reasons. for some reason this code does not digest and decrypt the encrypted file correctly.

Also, as I am pretty new in this field I have a pretty basic question, why is IV so important?

EDIT: I mistakenly wrote decrypt instead of encrypt, now I fixed this it seems to manage to decrypt the file other than the first 16 bytes, does this have something to do with the IV(my guess due tot the fact the IV is 16 bytes long)?

EDIT 2: Solved it by making the IV the first 16 bytes of the file instead of the same IV used for encoding, sorry for the hassle. Would love to get an answer on the reason and importance of the IV, if possible. thank you.

Isdj
  • 1,835
  • 1
  • 18
  • 36
  • @ArtjomB. Thank you, I corrected the code but still have an error. I used the filesize for the struct packing.. – Isdj Feb 24 '16 at 15:46
  • Possible duplicate of [AES decryption fails when decrypting a second time](http://stackoverflow.com/questions/33432775/aes-decryption-fails-when-decrypting-a-second-time) – Artjom B. Feb 24 '16 at 15:58

0 Answers0