from Crypto.Cipher import Blowfish
from Crypto.Util.Padding import pad, unpad
import os
import random
import string
import tkinter as tk
from tkinter import filedialog, messagebox
import pyperclip
import openpyxl # 用于处理 Excel 文件

def Blowfish_encrypt_decrypt(key, data, mode):
    # 获取块大小,并生成随机的初始向量
    bs = Blowfish.block_size
    iv = os.urandom(bs)
    # 创建Blowfish密码器并进行加密/解密操作
    cipher = Blowfish.new(key, mode, iv)
    data = pad(data, bs)  # 对数据进行填充
    encrypted_data = iv + cipher.encrypt(data)  # 添加初始向量,并加密数据
    return encrypted_data

def Blowfish_encrypt(key, data):
    # 使用CBC模式进行加密
    return Blowfish_encrypt_decrypt(key, data, Blowfish.MODE_CBC)

def Blowfish_decrypt(key, data):
    bs = Blowfish.block_size
    # 判断是否需要填充
    if len(data) % bs != 0:
        raise ValueError('Invalid data length. Data length must be a multiple of {} bytes.'.format(bs))
    # 获取初始向量和加密后的数据
    iv = data[:bs]
    encrypted_data = data[bs:]
    # 创建Blowfish密码器并进行解密操作
    cipher = Blowfish.new(key, Blowfish.MODE_CBC, iv)
    decrypted_data = cipher.decrypt(encrypted_data)
    # 去除填充
    unpadded_data = unpad(decrypted_data, bs)
    return unpadded_data

def validate_key(key):
    # 验证密钥长度是否符合要求
    key_length = len(key.encode())
    if key_length < 8 or key_length > 56 or key_length % 8 != 0:
        raise ValueError('Invalid key length. Key must be between 8 and 56 bytes, and a multiple of 8 bytes.')
    return key.encode()

def create_new_window3():
    def encrypt_file(input_file_path, output_file_path, key):
        # 验证密钥长度是否符合要求
        key = validate_key(key)
        # 读取输入文件并加密文件内容
        with open(input_file_path, 'rb') as f:
            data = f.read()
            encrypted_data = Blowfish_encrypt(key, data)
        # 将加密后的内容写入输出文件
        with open(output_file_path, 'wb') as f:
            f.write(encrypted_data)
        return True
    
    def decrypt_file(input_file_path, output_file_path, key):
        # 验证密钥长度是否符合要求
        key = validate_key(key)
        # 读取输入文件并解密文件内容
        with open(input_file_path, 'rb') as f:
            encrypted_data = f.read()
            decrypted_data = Blowfish_decrypt(key, encrypted_data)
        # 将解密后的内容写入输出文件
        with open(output_file_path, 'wb') as f:
            f.write(decrypted_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
        # 调用文件加密函数进行处理
        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
        # 调用文件解密函数进行处理
        if decrypt_file(input_file_path, output_file_path, key):
            messagebox.showinfo('Success', '文件解密成功!')
    
    def generate_random_key():
        # 生成随机密钥,包括字母和数字,长度为8
        key = ''.join(random.choices(string.ascii_letters + string.digits, k=8))
        return key
    
    # 用于生成密钥按钮的事件处理函数
    def on_generate_key():
        # 调用生成随机密钥函数生成密钥
        key = generate_random_key()
        # 清空密钥输入框并将生成的密钥赋值给输入框
        e_key.delete(0, tk.END)
        e_key.insert(0, key)
    
    # 复制按钮函数
    def on_copy_key():
        # 获取密钥
        key = e_key.get()
        if key:
            # 将密钥复制到剪贴板
            pyperclip.copy(key)
            messagebox.showinfo('Copied', '密钥已复制到剪贴板!')
            
    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():
        # 打开文件保存对话框,并设置默认文件扩展名为.xlsx
        file_path = filedialog.asksaveasfilename(defaultextension='.xlsx')
        if file_path:
            e_output.delete(0, tk.END)
            e_output.insert(0, file_path)
    
    # 创建主窗口
    root = tk.Tk()
    root.title('Blowfish 文件加密解密工具')
    
    # 创建标签和输入框
    label_input = tk.Label(root, text='输入文件路径:')
    label_input.grid(row=0, column=0, padx=5, pady=5)
    e_input = tk.Entry(root, width=50)
    e_input.grid(row=0, column=1, padx=5, pady=5)
    
    label_output = tk.Label(root, text='输出文件路径:')
    label_output.grid(row=1, column=0, padx=5, pady=5)
    e_output = tk.Entry(root, width=50)
    e_output.grid(row=1, column=1, padx=5, pady=5)
    
    label_key = tk.Label(root, text='密钥:')
    label_key.grid(row=2, column=0, padx=5, pady=5)
    e_key = tk.Entry(root, width=50)
    e_key.grid(row=2, column=1, padx=5, pady=5)
    
    # 创建按钮
    button_encrypt = tk.Button(root, text='加密', command=on_encrypt, width=10)
    button_encrypt.grid(row=3, column=0, padx=5, pady=5)
    button_decrypt = tk.Button(root, text='解密', command=on_decrypt, width=10)
    button_decrypt.grid(row=3, column=1, padx=5, pady=5)
    button_generate_key = tk.Button(root, text='生成密钥', command=on_generate_key, width=10)
    button_generate_key.grid(row=4, column=0, padx=5, pady=5)
    button_copy_key = tk.Button(root, text='复制密钥', command=on_copy_key, width=10)
    button_copy_key.grid(row=4, column=1, padx=5, pady=5)
    button_select_input = tk.Button(root, text='选择文件', command=on_select_input, width=10)
    button_select_input.grid(row=0, column=2, padx=5, pady=5)
    button_select_output = tk.Button(root, text='选择文件', command=on_select_output, width=10)
    button_select_output.grid(row=1, column=2, padx=5, pady=5)
    
    # 运行主循环
    root.mainloop()

# 处理 Excel 文件的示例
def encrypt_excel(input_file_path, output_file_path, key):
    # 验证密钥长度是否符合要求
    key = validate_key(key)
    
    # 读取 Excel 文件
    wb = load_workbook(filename=input_file_path)
    ws = wb.active
    data = []
    for row in ws.iter_rows(values_only=True):
        data.append(row)
    
    # 加密数据
    encrypted_data = []
    for row in data:
        encrypted_row = []
        for cell in row:
            if isinstance(cell, str):
                cell = cell.encode('utf-8')
            encrypted_cell = Blowfish_encrypt(key, cell)
            encrypted_row.append(encrypted_cell)
        encrypted_data.append(encrypted_row)
    
    # 创建新的 Excel 文件并写入加密后的数据
    wb_new = Workbook()
    ws_new = wb_new.active
    for row in encrypted_data:
        ws_new.append(row)
    wb_new.save(output_file_path)
    return True

def decrypt_excel(input_file_path, output_file_path, key):
    # 验证密钥长度是否符合要求
    key = validate_key(key)
    
    # 读取 Excel 文件
    wb = load_workbook(filename=input_file_path)
    ws = wb.active
    data = []
    for row in ws.iter_rows(values_only=True):
        data.append(row)
    
    # 解密数据
    decrypted_data = []
    for row in data:
        decrypted_row = []
        for cell in row:
            decrypted_cell = Blowfish_decrypt(key, cell)
            if isinstance(decrypted_cell, bytes):
                decrypted_cell = decrypted_cell.decode('utf-8')
            decrypted_row.append(decrypted_cell)
        decrypted_data.append(decrypted_row)
    
    # 创建新的 Excel 文件并写入解密后的数据
    wb_new = Workbook()
    ws_new = wb_new.active
    for row in decrypted_data:
        ws_new.append(row)
    wb_new.save(output_file_path)
    return True

# 使用示例
# encrypt_excel('input.xlsx', 'output.xlsx', 'your_key')
# decrypt_excel('input.xlsx', 'output.xlsx', 'your_key')

代码说明:

  1. 导入必要的库:

    • Crypto.Cipher.Blowfish: 用于 Blowfish 加密解密操作
    • Crypto.Util.Padding: 用于数据填充和去除填充
    • os: 用于生成随机初始向量
    • random: 用于生成随机密钥
    • string: 用于生成随机字符串
    • tkinter: 用于创建图形界面
    • tkinter.filedialog: 用于选择文件
    • tkinter.messagebox: 用于显示提示框
    • pyperclip: 用于复制密钥到剪贴板
    • openpyxl: 用于处理 Excel 文件
  2. Blowfish 加密解密函数:

    • Blowfish_encrypt_decrypt: 使用 Blowfish 算法进行加密或解密,支持 CBC 模式
    • Blowfish_encrypt: 使用 CBC 模式进行加密
    • Blowfish_decrypt: 使用 CBC 模式进行解密
  3. 密钥验证函数:

    • validate_key: 检查密钥长度是否符合要求(8-56 字节,且为 8 的倍数)
  4. 文件加密解密函数:

    • encrypt_file: 读取输入文件,使用 Blowfish 加密,并写入输出文件
    • decrypt_file: 读取输入文件,使用 Blowfish 解密,并写入输出文件
  5. 图形界面函数:

    • create_new_window3: 创建 GUI 窗口,包含文件路径输入框、密钥输入框、加密按钮、解密按钮、生成密钥按钮、复制密钥按钮、文件选择按钮等
  6. Excel 文件处理函数:

    • encrypt_excel: 读取 Excel 文件,使用 Blowfish 加密每个单元格,并写入新的 Excel 文件
    • decrypt_excel: 读取 Excel 文件,使用 Blowfish 解密每个单元格,并写入新的 Excel 文件

使用方法:

  1. 安装必要的库:pip install pycryptodome openpyxl pyperclip
  2. 运行代码,即可打开 GUI 窗口
  3. 选择要加密或解密的 Excel 文件
  4. 输入密钥或生成随机密钥
  5. 点击加密或解密按钮进行操作

注意:

  • 确保安装了必要的库
  • 密钥用于加密和解密,请妥善保管
  • 密钥长度必须符合要求,否则会抛出异常
  • 加密后的文件需要使用相同的密钥进行解密
Blowfish 加密解密库 - Python 文件加密解密工具

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

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