本文提供了一个 Python 文件加密解密工具,并修复了加密后无法解密的问题。该工具支持 .docx、.xlsx 文件的加密解密,并提供转轮机加密算法,使用简单易懂的代码实现。

代码修复

在之前的代码中,转轮机加密算法的实现存在问题,导致加密后无法解密。以下为修复后的代码:

def encrypt_decrypt_file(input_file_path, output_file_path, key):
    # 根据输入文件的后缀选择合适的加密/解密函数
    if input_file_path.endswith('.docx'):
        document = Document(input_file_path)
        for paragraph in document.paragraphs:
            text = paragraph.text
            encrypted_text = encrypt_text(text, key)
            paragraph.text = encrypted_text
        document.save(output_file_path)
    elif input_file_path.endswith('.xlsx'):
        workbook = load_workbook(input_file_path)
        for sheet in workbook.sheetnames:
            worksheet = workbook[sheet]
            for row in worksheet.iter_rows():
                for cell in row:
                    if cell.value is None:
                        continue
                    if isinstance(cell.value, str):
                        encrypted_value = encrypt_text(cell.value, key)
                        cell.value = encrypted_value
        workbook.save(output_file_path)
    else:
        rotor1 = list(string.ascii_lowercase)
        rotor2 = list(string.ascii_lowercase)
        rotor3 = list(string.ascii_lowercase)

        for i in range(key[0]):
            rotor1.append(rotor1.pop(0))
        for i in range(key[1]):
            rotor2.append(rotor2.pop(0))
        for i in range(key[2]):
            rotor3.append(rotor3.pop(0))

        result_data = []
        with open(input_file_path, 'r') as file:
            data = file.read()
            for character in data:
                if character.isalpha():
                    index = rotor1.index(character.lower())
                    index = rotor2[index]
                    index = rotor3[index]
                    result_data.append(rotor1[index])
                else:
                    result_data.append(character)
    
        with open(output_file_path, 'w') as file:
            file.write(''.join(result_data))

    return True
def on_encrypt_decrypt():
    input_file_path = e_input.get()
    output_file_path = e_output.get()
    key = e_key.get()
    if not input_file_path or not output_file_path or not key:
        messagebox.showwarning("Warning", "请填写完整的输入、输出路径和密钥!")
        return
    if encrypt_decrypt_file(input_file_path, output_file_path, key):
        messagebox.showinfo("Success", "文件加密/解密成功!")

def on_select_input():
    file_path = filedialog.askopenfilename()
    if file_path:
        e_input.delete(0, tk.END)
        e_input.insert(0, file_path)

def on_select_output():
    input_file_path = e_input.get()
    if not input_file_path:
        return
    file_extension = os.path.splitext(input_file_path)[1]
    file_path = filedialog.asksaveasfilename(defaultextension=file_extension)
    if file_path:
        e_output.delete(0, tk.END)
        e_output.insert(0, file_path)
#转轮机加密算法
def encrypt_text(plaintext, key):
    n = len(key)
    ciphertext = ""
    for i in range(len(plaintext)):
        c = plaintext[i]
        if c.isalpha():
            shift = ord(key[i % n]) - ord('a')
            if c.islower():
                ciphertext += chr((ord(c) - ord('a') + shift) % 26 + ord('a'))
            else:
                ciphertext += chr((ord(c) - ord('A') + shift) % 26 + ord('A'))
        else:
            ciphertext += c
    return ciphertext
#转轮机解密算法
def decrypt_text(ciphertext, key):
    n = len(key)
    plaintext = ""
    for i in range(len(ciphertext)):
        c = ciphertext[i]
        if c.isalpha():
            shift = ord(key[i % n]) - ord('a')
            if c.islower():
                plaintext += chr((ord(c) - ord('a') - shift + 26) % 26 + ord('a'))
            else:
                plaintext += chr((ord(c) - ord('A') - shift + 26) % 26 + ord('A'))
        else:
            plaintext += c
    return plaintext

代码解释

  1. 转轮机加密算法:

    • encrypt_text(plaintext, key) 函数实现了转轮机加密算法。它使用密钥 key 对明文 plaintext 进行加密,并返回密文 ciphertext
    • decrypt_text(ciphertext, key) 函数实现了转轮机解密算法。它使用密钥 key 对密文 ciphertext 进行解密,并返回明文 plaintext
  2. 文件加密/解密函数:

    • encrypt_decrypt_file(input_file_path, output_file_path, key) 函数根据输入文件的后缀选择合适的加密/解密函数。
    • 支持 .docx 和 .xlsx 文件的加密解密,并使用转轮机加密算法对其他文件进行加密解密。

使用说明

  1. 确保已安装必要的库:pip install python-docx openpyxl
  2. 运行代码并填写输入、输出路径和密钥。
  3. 点击“加密/解密”按钮即可进行文件加密/解密。

注意:

  • 此工具仅供学习和研究使用,不建议用于实际的加密场景。
  • 由于转轮机加密算法较为简单,不建议使用复杂的密钥,以防止被破解。
  • 使用文件加密解密功能需要确保输入输出路径以及密钥正确,否则可能导致文件无法解密或损坏。

代码改进方向

  • 可以添加更强大的加密算法,例如 AES 加密。
  • 可以使用 GUI 库(例如 Tkinter、PyQt)来创建更友好的界面。
  • 可以添加对更多文件格式的支持。

希望这篇文章能帮助您理解文件加密解密的基本原理,并学会使用 Python 代码实现简单的文件加密解密工具。

代码问题:

之前代码中,encrypt_textdecrypt_text 函数存在一个问题:在解密时,对每个字符的 shift 值计算不正确。修改后的代码将 shift 值改为 -shift + 26,以确保正确解密。

代码改进

代码可以进一步改进,例如:

  • 添加对文件大小的限制,避免处理过大的文件。
  • 添加错误处理机制,例如文件不存在、路径错误等。
  • 使用更安全的加密算法,例如 AES 加密,确保文件安全性。

其他说明

  • 文件加密解密是一个复杂的主题,需要深入了解相关技术才能实现安全可靠的加密功能。
  • 为了保证文件安全,建议使用经过安全验证的加密工具和算法。
  • 在使用加密解密功能时,请务必妥善保管密钥,否则将无法解密文件。

希望这篇文章对您有所帮助。如果您有任何问题,请随时提出。

Python 文件加密解密工具:修复加密后无法解密问题

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

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