Python 文件加密解密函数实现

以下代码使用简单的异或操作进行文件加密和解密,并针对 .docx 和 .xlsx 文件格式分别使用 python-docx 和 openpyxl 库进行保存。

加密函数:

def encrypt_file(input_file_path, output_file_path, key):
    try:
        with open(input_file_path, 'rb') as input_file:
            with open(output_file_path, 'wb') as output_file:
                while True:
                    byte = input_file.read(1)
                    if not byte:
                        break
                    encrypted_byte = ord(byte) ^ int(key)
                    output_file.write(bytes([encrypted_byte]))
        # 根据输出文件的扩展名选择保存方式
        file_extension = os.path.splitext(output_file_path)[1]
        temp_file_path = output_file_path.replace(file_extension, '_temp' + file_extension)
        os.rename(output_file_path, temp_file_path)
        if file_extension == '.docx':
            # 如果是 .docx 文件,则使用 python-docx 库保存
            doc = docx.Document(temp_file_path)
            doc.save(output_file_path)
        elif file_extension == '.xlsx':
            # 如果是 .xlsx 文件,则使用 openpyxl 库保存
            wb = openpyxl.load_workbook(temp_file_path)
            wb.save(output_file_path)
        os.remove(temp_file_path)
        return True
    except Exception as e:
        messagebox.showerror('Error', str(e))
        return False

解密函数:

def decrypt_file(input_file_path, output_file_path, key):
    try:
        with open(input_file_path, 'rb') as input_file:
            with open(output_file_path, 'wb') as output_file:
                while True:
                    byte = input_file.read(1)
                    if not byte:
                        break
                    decrypted_byte = ord(byte) ^ int(key)
                    output_file.write(bytes([decrypted_byte]))
        # 根据输出文件的扩展名选择保存方式
        file_extension = os.path.splitext(output_file_path)[1]
        temp_file_path = output_file_path.replace(file_extension, '_temp' + file_extension)
        os.rename(output_file_path, temp_file_path)
        if file_extension == '.docx':
            # 如果是 .docx 文件,则使用 python-docx 库保存
            doc = docx.Document(temp_file_path)
            doc.save(output_file_path)
        elif file_extension == '.xlsx':
            # 如果是 .xlsx 文件,则使用 openpyxl 库保存
            wb = openpyxl.load_workbook(temp_file_path)
            wb.save(output_file_path)
        os.remove(temp_file_path)
        return True
    except Exception as e:
        messagebox.showerror('Error', str(e))
        return False

常见错误及解决方法

错误:file is not a zip file

这个错误通常是由于尝试对非zip压缩文件进行解压缩操作引起的,可能是因为文件扩展名不正确或文件本身已经被损坏。

解决方案:

  1. 检查文件扩展名是否正确,确保输入的是正确的文件类型。
  2. 尝试使用其他文件打开工具打开文件,检查文件是否已经被损坏。
  3. 如果文件确实是zip压缩文件,则可以尝试使用Python的zipfile库进行解压缩操作。

以下代码使用 zipfile 库进行解压缩:

import zipfile

def decrypt_file(input_file_path, output_file_path, key):
    try:
        with zipfile.ZipFile(input_file_path, 'r') as zip_file:
            with open(output_file_path, 'wb') as output_file:
                for name in zip_file.namelist():
                    with zip_file.open(name) as input_file:
                        while True:
                            byte = input_file.read(1)
                            if not byte:
                                break
                            decrypted_byte = ord(byte) ^ int(key)
                            output_file.write(bytes([decrypted_byte]))
        return True
    except Exception as e:
        messagebox.showerror('Error', str(e))
        return False

注意: 这个方法仅适用于zip压缩文件,如果输入文件不是zip压缩文件,则仍然会出现错误。

使用说明

  1. 安装必要的库:python-docx, openpyxl, zipfile
  2. 将以上代码保存为 Python 文件。
  3. 使用 encrypt_file 函数进行文件加密,使用 decrypt_file 函数进行文件解密。
  4. 传入正确的文件路径、输出路径和密钥。
  5. 运行代码即可完成文件加密解密操作。

代码示例

import os
import docx
import openpyxl
import zipfile
from tkinter import messagebox

# 示例:加密 .docx 文件
encrypt_file('input.docx', 'output.docx', '1234')

# 示例:解密 .xlsx 文件
decrypt_file('input.xlsx', 'output.xlsx', '1234')

注意事项

  1. 此代码使用简单的异或操作进行加密,安全性较低,仅供学习参考。
  2. 在实际应用中,请使用更加安全的加密算法。
  3. 请妥善保管密钥,不要泄露给其他人。

希望本文对你有所帮助。如有任何疑问,请随时留言。

Python 文件加密解密函数实现 - 支持 .docx 和 .xlsx 文件

原文地址: https://www.cveoy.top/t/topic/oRTb 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录