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 key_expander_256 = KeyExpander(256) expanded_key = key_expander_256.expand(self._key) aes_cipher_256 = AESCipher(expanded_key) aes_cbc_256 = CBCMode(aes_cipher_256, 16) 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 = bytearray(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(self.fix_bytes( out_data[:filesize - out_file.tell()] if filesize - out_file.tell() < 16 else out_file.write(self.fix_bytes(out_data))))
def encrypt_file(self, in_file_path, out_file_path, password = None): #If a password is provided, generate new salt and create key and iv if password is not None: self.new_salt() self.create_key_from_password(password) else: self._salt = None #If key and iv are not provided are established above, bail out. if self._key is None or self._iv is None: return False #Initialize encryption using key and iv key_expander_256 = KeyExpander(256) expanded_key = key_expander_256.expand(self._key) aes_cipher_256 = AESCipher(expanded_key) aes_cbc_256 = CBCMode(aes_cipher_256, 16) aes_cbc_256.set_iv(self._iv) #Get filesize of original file for storage in encrypted file try: filesize = os.stat(in_file_path)[6] except: return False with open(in_file_path, 'rb') as in_file: with open(out_file_path, 'wb') as out_file: #Write salt if present if self._salt is not None: out_file.write(self._salt) #Write filesize of original out_file.write(struct.pack('L',filesize)) #Encrypt to eof while 1: in_data = in_file.read(16) if not in_data: self._salt = None return True else: out_data = aes_cbc_256.encrypt_block(bytearray(in_data)) out_file.write(self.fix_bytes(out_data))