import os
import string
from docx import Document
from openpyxl import load_workbook
import tkinter as tk
from tkinter import filedialog
from tkinter import messagebox

def encrypt_file(input_file_path, output_file_path, key):
    # 根据输入文件的后缀选择合适的加密函数
    if input_file_path.endswith('.docx'):
        # 如果是.docx文件,使用Python库docx对文本进行加密
        document = Document(input_file_path)
        for paragraph in document.paragraphs:
            text = paragraph.text
            encrypted_text = encrypt_text(text, key) #调用encrypt_text函数进行加密操作
            paragraph.text = encrypted_text
        document.save(output_file_path)#保存加密后的文件
    elif input_file_path.endswith('.xlsx'):
        #如果是.xlsx文件,使用Python库openpyxl对单元格数据进行加密
        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)#调用encrypt_text函数进行加密操作
                        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 decrypt_file(input_file_path, output_file_path, key):
    # 根据输入文件的后缀选择合适的解密函数
    if input_file_path.endswith('.docx'):
        # 如果是.docx文件,使用Python库docx对文本进行解密
        document = Document(input_file_path)
        for paragraph in document.paragraphs:
            text = paragraph.text
            decrypted_text = decrypt_text(text, key) #调用decrypt_text函数进行解密操作
            paragraph.text = decrypted_text
        document.save(output_file_path)#保存解密后的文件
    elif input_file_path.endswith('.xlsx'):
        #如果是.xlsx文件,使用Python库openpyxl对单元格数据进行解密
        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):
                        decrypted_value = decrypt_text(cell.value, key)#调用decrypt_text函数进行解密操作
                        cell.value = decrypted_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)#将结果作为索引在第二个转子中查找
                    index = rotor3.index(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():
    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
    #调用encrypt_file函数进行文件加密操作
    if encrypt_file(input_file_path, output_file_path, key):
        messagebox.showinfo("Success", "文件加密成功!")

def on_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
    #调用decrypt_file函数进行文件解密操作
    if 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'))#加上偏移量,并对26取余得到新的字符位置
            else:#如果是大写字母
                ciphertext += chr((ord(c) - ord('A') + shift) % 26 + ord('A'))#加上偏移量,并对26取余得到新的字符位置
        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'))#减掉偏移量,并对26取余得到新的字符位置
            else:#如果是大写字母
                plaintext += chr((ord(c) - ord('A') - shift + 26) % 26 + ord('A'))#减掉偏移量,并对26取余得到新的字符位置
        else:
            plaintext += c#非字母字符直接添加到密文中
    return plaintext

点击加密按钮后,导出的文件和原文件一样(未加密),提供解决代码内容:可能是因为在加密和解密函数中,对于非字母字符直接添加到结果数据中,但是在写入文件时并没有进行处理,导致非字母字符被省略了。可以在写入文件时添加一个判断,如果是非字母字符,则直接写入,否则进行加密或解密操作后再写入。

修改后的代码如下:

import os
import string
from docx import Document
from openpyxl import load_workbook
import tkinter as tk
from tkinter import filedialog
from tkinter import messagebox

def encrypt_file(input_file_path, output_file_path, key):
    # 根据输入文件的后缀选择合适的加密函数
    if input_file_path.endswith('.docx'):
        # 如果是.docx文件,使用Python库docx对文本进行加密
        document = Document(input_file_path)
        for paragraph in document.paragraphs:
            text = paragraph.text
            encrypted_text = encrypt_text(text, key) #调用encrypt_text函数进行加密操作
            paragraph.text = encrypted_text
        document.save(output_file_path)#保存加密后的文件
    elif input_file_path.endswith('.xlsx'):
        #如果是.xlsx文件,使用Python库openpyxl对单元格数据进行加密
        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)#调用encrypt_text函数进行加密操作
                        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 decrypt_file(input_file_path, output_file_path, key):
    # 根据输入文件的后缀选择合适的解密函数
    if input_file_path.endswith('.docx'):
        # 如果是.docx文件,使用Python库docx对文本进行解密
        document = Document(input_file_path)
        for paragraph in document.paragraphs:
            text = paragraph.text
            decrypted_text = decrypt_text(text, key) #调用decrypt_text函数进行解密操作
            paragraph.text = decrypted_text
        document.save(output_file_path)#保存解密后的文件
    elif input_file_path.endswith('.xlsx'):
        #如果是.xlsx文件,使用Python库openpyxl对单元格数据进行解密
        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):
                        decrypted_value = decrypt_text(cell.value, key)#调用decrypt_text函数进行解密操作
                        cell.value = decrypted_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)#将结果作为索引在第二个转子中查找
                    index = rotor3.index(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

Python 文件加密解密工具 - 支持 .docx, .xlsx 和自定义转子密码加密

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

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