Python 文件加密解密工具:支持 Word、Excel 和自定义加密算法
以下是使用 Python 实现的简单文件加密解密工具,支持 Word (.docx)、Excel (.xlsx) 文件以及自定义转轮机加密算法。
import os
import tkinter as tk
from tkinter import filedialog, messagebox
from docx import Document
from openpyxl import load_workbook
import string
# 文件加密解密函数
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
# 创建GUI界面
root = tk.Tk()
root.title("文件加密解密工具")
# 输入文件路径
label_input = tk.Label(root, text="输入文件路径:")
label_input.grid(row=0, column=0)
e_input = tk.Entry(root, width=50)
e_input.grid(row=0, column=1)
button_select_input = tk.Button(root, text="选择文件", command=on_select_input)
button_select_input.grid(row=0, column=2)
# 输出文件路径
label_output = tk.Label(root, text="输出文件路径:")
label_output.grid(row=1, column=0)
e_output = tk.Entry(root, width=50)
e_output.grid(row=1, column=1)
button_select_output = tk.Button(root, text="选择路径", command=on_select_output)
button_select_output.grid(row=1, column=2)
# 密钥
label_key = tk.Label(root, text="密钥:")
label_key.grid(row=2, column=0)
e_key = tk.Entry(root, width=50)
e_key.grid(row=2, column=1)
# 加密解密按钮
button_encrypt_decrypt = tk.Button(root, text="加密/解密", command=on_encrypt_decrypt)
button_encrypt_decrypt.grid(row=3, column=1)
root.mainloop()
代码说明:
- 文件加密解密函数 (
encrypt_decrypt_file):- 根据输入文件后缀名判断文件类型:
.docx:使用docx库对 Word 文件进行加密解密;.xlsx:使用openpyxl库对 Excel 文件进行加密解密;- 其他类型:使用自定义的转轮机加密算法进行加密解密。
- 根据输入文件后缀名判断文件类型:
- 转轮机加密算法 (
encrypt_text,decrypt_text):- 基于凯撒密码扩展,使用三个转轮进行字符替换,密钥为三个字母,分别对应三个转轮的旋转次数。
- GUI 界面:
- 使用
tkinter库创建简单的 GUI 界面,方便用户选择文件路径、设置密钥以及执行加密解密操作。
- 使用
加密解密原理:
- Word 和 Excel 文件加密解密:
- 使用
docx和openpyxl库对文件内容进行直接操作,将文本或单元格内容进行加密或解密。
- 使用
- 转轮机加密算法:
- 使用三个转轮,每个转轮对应一个字母,通过旋转转轮来对字母进行替换加密,解密时按照相反的顺序旋转转轮即可。
使用说明:
- 将代码保存为
.py文件。 - 运行代码,打开 GUI 界面。
- 选择要加密或解密的文件路径。
- 输入密钥(三个字母)。
- 点击 "加密/解密" 按钮执行操作。
注意事项:
- 此工具仅供学习参考,安全性有限。
- 使用自定义转轮机加密算法时,请确保密钥长度为三个字母,否则会出错。
- 对于其他格式的文件,需要根据具体格式编写相应的加密解密代码。
加密再解密后的文件内容和原文件不一样可能是因为加密和解密使用的密钥不同或者加密算法本身存在问题。另外,如果加密解密文件的过程中出现了文件格式转换问题,也可能导致最终文件内容不一致。需要仔细检查代码实现和输入输出参数,确保每个步骤都正确执行。
原文地址: https://www.cveoy.top/t/topic/oIko 著作权归作者所有。请勿转载和采集!