使用 Python 和 IDEA 算法加密解密文件

本代码使用 Python 和 IDEA 算法实现文件加密和解密功能。提供了一个简单的图形用户界面,允许用户选择要加密或解密的文件或文件夹,并提供密钥。

代码实现

import os
import tkinter as tk
from tkinter import filedialog, messagebox
from win32com.client import Dispatch
from Crypto.Cipher import IDEA


# 密钥为16字节
key = b'1234567890abcdef'


# 加密word文件
def encrypt_word_file(file_path):
    word = Dispatch('Word.Application')  # 打开Word
    word.Visible = 0  # 隐藏窗口
    doc = word.Documents.Open(file_path)  # 打开文件
    doc.SaveAs(file_path + '.encrypted', FileFormat=16)  # 另存为加密文件
    doc.Close()
    word.Quit()

    # 加密文件内容
    with open(file_path + '.encrypted', 'rb') as f:
        data = f.read()
        encrypt_data = IDEA_encrypt_decrypt(key, data, IDEA.MODE_ENCRYPT)

    with open(file_path + '.encrypted', 'wb') as f:
        f.write(encrypt_data)

    return file_path + '.encrypted'


# 加密Excel文件
def encrypt_excel_file(file_path):
    excel = Dispatch('Excel.Application')  # 打开Excel
    excel.Visible = 0  # 隐藏窗口
    wb = excel.Workbooks.Open(file_path)  # 打开文件
    wb.SaveAs(file_path + '.encrypted', FileFormat=51)  # 另存为加密文件
    wb.Close()
    excel.Quit()

    # 加密文件内容
    with open(file_path + '.encrypted', 'rb') as f:
        data = f.read()
        encrypt_data = IDEA_encrypt_decrypt(key, data, IDEA.MODE_ENCRYPT)

    with open(file_path + '.encrypted', 'wb') as f:
        f.write(encrypt_data)

    return file_path + '.encrypted'


# 加密/解密文件内容
def IDEA_encrypt_decrypt(key, data, mode):
    cipher = IDEA.new(key, mode)
    encrypted_data = cipher.encrypt(data) if mode == IDEA.MODE_ENCRYPT else cipher.decrypt(data)
    return encrypted_data


# 加密/解密文件
def encrypt_decrypt_file(file_path, mode):
    with open(file_path, 'rb') as f:
        data = f.read()
        encrypt_data = IDEA_encrypt_decrypt(key, data, mode)

    with open(file_path, 'wb') as f:
        f.write(encrypt_data)


# 加密/解密指定文件夹下的所有文件
def encrypt_decrypt_folder(folder_path, mode):
    for file_name in os.listdir(folder_path):
        file_path = os.path.join(folder_path, file_name)
        if os.path.isdir(file_path):
            encrypt_decrypt_folder(file_path, mode)
        else:
            if file_name.endswith('.docx'):
                file_path = encrypt_word_file(file_path) if mode == IDEA.MODE_ENCRYPT else file_path.replace('.encrypted', '')
            elif file_name.endswith('.xlsx'):
                file_path = encrypt_excel_file(file_path) if mode == IDEA.MODE_ENCRYPT else file_path.replace('.encrypted', '')
            else:
                file_path = file_path

            encrypt_decrypt_file(file_path, mode)


# 加密指定文件夹下的所有文件
def encrypt_folder(folder_path):
    encrypt_decrypt_folder(folder_path, IDEA.MODE_ENCRYPT)


# 解密指定文件夹下的所有文件
def decrypt_folder(folder_path):
    encrypt_decrypt_folder(folder_path, IDEA.MODE_DECRYPT)


# 实际执行文件加密/解密操作
def encrypt_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:
                    chunk = input_file.read(1024)
                    if not chunk:
                        break
                    encrypted_chunk = IDEA_encrypt_decrypt(key, chunk, IDEA.MODE_ENCRYPT)
                    output_file.write(encrypted_chunk)
        return True
    except Exception as e:
        messagebox.showerror('Error', str(e))
        return False


# 检查输入框是否填写完整,然后调用encrypt_decrypt_file函数进行加密/解密操作
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.encode()):
        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():
    file_path = filedialog.asksaveasfilename(defaultextension='.dat')
    if file_path:
        e_output.delete(0, tk.END)
        e_output.insert(0, file_path)


# 创建主窗口
root_new = tk.Tk()
root_new.title('IDEA算法加密/解密工具')
root_new.geometry('500x300')

# 输入文件路径
lbl_input = tk.Label(root_new, text='输入文件路径:')
lbl_input.pack()
e_input = tk.Entry(root_new, width=50)
e_input.pack()
btn_select_input = tk.Button(root_new, text='选择文件', command=on_select_input)
btn_select_input.pack()

# 输出文件路径
lbl_output = tk.Label(root_new, text='输出文件路径:')
lbl_output.pack()
e_output = tk.Entry(root_new, width=50)
e_output.pack()
btn_select_output = tk.Button(root_new, text='选择路径', command=on_select_output)
btn_select_output.pack()

# 密钥
lbl_key = tk.Label(root_new, text='密钥:')
lbl_key.pack()
e_key = tk.Entry(root_new)
e_key.pack()

# 加密/解密按钮
btn_encrypt_decrypt = tk.Button(root_new, text='加密/解密', command=on_encrypt_decrypt)
btn_encrypt_decrypt.pack()

root_new.mainloop()

功能介绍

  1. 加密和解密单个文件: 用户可以选择要加密或解密的单个文件,并指定输出文件路径和密钥。
  2. 加密和解密整个文件夹: 用户可以选择要加密或解密的文件夹,代码将递归遍历所有文件并执行加密或解密操作。
  3. 支持 Word 和 Excel 文件: 代码可以加密和解密 Word (.docx) 和 Excel (.xlsx) 文件。
  4. 用户友好界面: 代码使用 Tkinter 库创建一个简单的图形界面,方便用户操作。

使用说明

  1. 安装必要的库:
    pip install pywin32 pycryptodome
    
  2. 运行 Python 代码。
  3. 在界面中选择要加密或解密的文件或文件夹,并输入密钥。
  4. 点击“加密/解密”按钮开始操作。

注意事项

  1. 密钥必须为 16 字节。
  2. 加密后的文件会以“.encrypted”为扩展名。
  3. 解密操作需要使用与加密时相同的密钥。
  4. 代码仅支持 Windows 平台。

进一步改进

  1. 添加进度条显示加密或解密进度。
  2. 支持更多文件类型。
  3. 支持命令行模式。
  4. 增强安全性,例如使用更复杂的加密算法或使用随机生成的密钥。

本代码提供了一个简单的文件加密和解密方案,您可以根据需要进行调整和改进。请注意,任何加密方案都存在被破解的风险,重要的是要使用强大的加密算法并妥善保管密钥。

IDEA 算法加密解密工具 - 使用 Python 加密和解密文件

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

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