예제 #1
0
파일: demo.py 프로젝트: serprex/pythonaes
    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
        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)

        #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 = bytearray(in_file.read(16))
                    if not in_data:
                        self._salt = None
                        return True
                    else:
                        while len(in_data) < 16:in_data.append(0)
                        out_data = aes_cbc_256.encrypt_block(in_data)
                        out_file.write(fix_bytes(out_data))