转轮机密码窗口 - 文件加密解密工具

本程序使用转轮机密码算法对文件进行加密解密,支持多种文件格式,如.docx、.xlsx等,并提供图形界面操作。

代码实现

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

def create_new_window1():
    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)

    #创建主窗口
    window = tk.Tk()
    window.title('转轮机密码窗口')

    #创建输入路径文本框
    label_input = tk.Label(window, text='输入文件路径:')
    label_input.grid(row=0, column=0, padx=5, pady=5)
    e_input = tk.Entry(window, width=50)
    e_input.grid(row=0, column=1, padx=5, pady=5)
    button_select_input = tk.Button(window, text='选择文件', command=on_select_input)
    button_select_input.grid(row=0, column=2, padx=5, pady=5)

    #创建输出路径文本框
    label_output = tk.Label(window, text='输出文件路径:')
    label_output.grid(row=1, column=0, padx=5, pady=5)
    e_output = tk.Entry(window, width=50)
    e_output.grid(row=1, column=1, padx=5, pady=5)
    button_select_output = tk.Button(window, text='选择保存路径', command=on_select_output)
    button_select_output.grid(row=1, column=2, padx=5, pady=5)

    #创建密钥文本框
    label_key = tk.Label(window, text='密钥:')
    label_key.grid(row=2, column=0, padx=5, pady=5)
    e_key = tk.Entry(window, width=50)
    e_key.grid(row=2, column=1, padx=5, pady=5)

    #创建加密按钮
    button_encrypt = tk.Button(window, text='加密', command=on_encrypt, width=10)
    button_encrypt.grid(row=3, column=0, padx=5, pady=5)

    #创建解密按钮
    button_decrypt = tk.Button(window, text='解密', command=on_decrypt, width=10)
    button_decrypt.grid(row=3, column=1, padx=5, pady=5)

    window.mainloop()

#转轮机加密算法
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

#对xlsx文件无法进行加密,提供解决的代码内容:以下是对excel文件进行加密的代码:

```python
#转轮机加密算法
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

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

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

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