예제 #1
0
파일: demo.py 프로젝트: serprex/pythonaes
    def decrypt_file(self, in_file_path, out_file_path, password = None):
        with open(in_file_path, 'rb') as in_file:

            #If a password is provided, generate key and iv using salt from file.
            if password is not None:
                self._salt = in_file.read(32)
                self.create_key_from_password(password)

            #Key and iv have not been generated or provided, bail out
            if self._key is None or self._iv is None:
                return False

            #Initialize encryption using key and iv
            expanded_key = expandKey(self._key)
            aes_cipher_256 = AESCipher(expanded_key)
            aes_cbc_256 = CBCMode(aes_cipher_256)
            aes_cbc_256.set_iv(self._iv)

            #Read original file size
            filesize = struct.unpack('!L',in_file.read(4))[0]

            #Decrypt to eof
            with open(out_file_path, 'wb') as out_file:
                while 1:
                    in_data = in_file.read(16)
                    if not in_data:
                        self._salt = None
                        return True
                    else:
                        out_data = aes_cbc_256.decrypt_block(bytearray(in_data))
                        #At end of file, if end of original file is within < 16 bytes slice it out.
                        out_file.write(fix_bytes(
                            out_data[:filesize - out_file.tell()] if filesize - out_file.tell() < 16
                            else fix_bytes(out_data)))