流密码加密解密窗口 - Python 代码实现
流密码加密解密窗口 - Python 代码实现
本文提供使用 Python 代码实现流密码加密解密功能的示例,并创建图形界面窗口方便用户操作。代码示例包含以下功能:
- 文件加密解密函数:
encrypt_file和decrypt_file函数用于执行文件加密和解密操作。 - 流密码加密解密函数:
stream_cipher_encrypt和stream_cipher_decrypt函数用于实现流密码的加密和解密算法。 - 密钥流生成函数:
generate_keystream函数用于生成密钥流。 - 图形界面: 使用 Tkinter 库创建图形界面窗口,包含输入文件路径、输出文件路径、密钥输入框、加密按钮和解密按钮。
代码示例
import tkinter as tk
from tkinter import filedialog, messagebox
import os
import docx
import openpyxl
def create_new_window2():
#此函数用于实际执行文件加密操作
def encrypt_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:
# 读取整个文件内容
plaintext = input_file.read().decode() # 将bytes类型转换为字符串类型
# 对明文进行流密码加密
ciphertext = stream_cipher_encrypt(plaintext, key)
# 将密文写入输出文件
output_file.write(ciphertext.encode())
# 根据输出文件的扩展名选择保存方式
file_extension = os.path.splitext(output_file_path)[1]
if file_extension == '.docx':
#如果是.docx文件,则使用python-docx库保存
doc = docx.Document(output_file_path)
doc.save(output_file_path)
elif file_extension == '.xlsx':
#如果是.xlsx文件,则使用openpyxl库保存
wb = openpyxl.load_workbook(output_file_path)
wb.save(output_file_path)
return True
except Exception as e:
messagebox.showerror('Error', str(e))
return False
def 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:
# 读取整个文件内容
ciphertext = input_file.read().decode() # 将bytes类型转换为字符串类型
# 对密文进行流密码解密
plaintext = stream_cipher_decrypt(ciphertext, key)
# 将明文写入输出文件
output_file.write(plaintext.encode())
# 根据输出文件的扩展名选择保存方式
file_extension = os.path.splitext(output_file_path)[1]
if file_extension == '.docx':
#如果是.docx文件,则使用python-docx库保存
doc = docx.Document(output_file_path)
doc.save(output_file_path)
elif file_extension == '.xlsx':
#如果是.xlsx文件,则使用openpyxl库保存
wb = openpyxl.load_workbook(output_file_path)
wb.save(output_file_path)
return True
except Exception as e:
messagebox.showerror('Error', str(e))
return False
#此函数可以检查输入框是否填写完整,然后调用encrypt_file函数进行加密操作
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', '文件加密成功!')
#此函数可以检查输入框是否填写完整,然后调用decrypt_file函数进行解密操作
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)
new_window = tk.Toplevel(root_new)
new_window.title('流密码加密\解密窗口')
new_window.geometry('2000x1000')
# 输入文件路径
lbl_input = tk.Label(new_window, text='输入文件路径:')
lbl_input.pack()
e_input = tk.Entry(new_window, width=50)
e_input.pack()
btn_select_input = tk.Button(new_window, text='选择文件', command=on_select_input)
btn_select_input.pack()
# 输出文件路径
lbl_output = tk.Label(new_window, text='输出文件路径:')
lbl_output.pack()
e_output = tk.Entry(new_window, width=50)
e_output.pack()
btn_select_output = tk.Button(new_window, text='选择路径', command=on_select_output)
btn_select_output.pack()
# 密钥
lbl_key = tk.Label(new_window, text='密钥:')
lbl_key.pack()
e_key = tk.Entry(new_window)
e_key.pack()
# 加密按钮
btn_encrypt = tk.Button(new_window, text='加密', command=on_encrypt)
btn_encrypt.pack()
# 解密按钮
btn_decrypt = tk.Button(new_window, text='解密', command=on_decrypt)
btn_decrypt.pack()
def stream_cipher_encrypt(plaintext, key):
# 初始化密钥流生成器
keystream = generate_keystream(key, len(plaintext))
# 对明文与密钥流进行异或运算,得到密文
ciphertext = [chr(ord(p) ^ k) for p, k in zip(plaintext, keystream)]
# 返回密文
return ''.join(ciphertext)
def stream_cipher_decrypt(ciphertext, key):
# 初始化密钥流生成器
keystream = generate_keystream(key, len(ciphertext))
# 对密文与密钥流进行异或运算,得到明文
plaintext = [chr(ord(c) ^ k) for c, k in zip(ciphertext, keystream)]
# 返回明文
return ''.join(plaintext)
def generate_keystream(key, length):
# 初始化状态向量
S = list(range(256))
j = 0
# 密钥调度算法
for i in range(256):
j = (j + S[i] + ord(key[i % len(key)])) % 256
S[i], S[j] = S[j], S[i]
# 生成密钥流
keystream = []
i = j = 0
for _ in range(length):
i = (i + 1) % 256
j = (j + S[i]) % 256
S[i], S[j] = S[j], S[i]
keystream.append(S[(S[i] + S[j]) % 256])
# 返回密钥流
return keystream
错误解决
在加密过程中,可能会遇到 ord() expected string of length 1, but int found 错误。这是因为在 encrypt_file 和 decrypt_file 函数中,读取文件时使用了 rb 和 wb 模式,返回的是 bytes 类型,但是在调用 stream_cipher_encrypt 和 stream_cipher_decrypt 函数时,传入的参数为字符串类型,需要先将读取的 bytes 类型转换为字符串类型。
以下为修改后的 encrypt_file 和 decrypt_file 函数代码:
def encrypt_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:
# 读取整个文件内容
plaintext = input_file.read().decode() # 将bytes类型转换为字符串类型
# 对明文进行流密码加密
ciphertext = stream_cipher_encrypt(plaintext, key)
# 将密文写入输出文件
output_file.write(ciphertext.encode())
# 根据输出文件的扩展名选择保存方式
file_extension = os.path.splitext(output_file_path)[1]
if file_extension == '.docx':
#如果是.docx文件,则使用python-docx库保存
doc = docx.Document(output_file_path)
doc.save(output_file_path)
elif file_extension == '.xlsx':
#如果是.xlsx文件,则使用openpyxl库保存
wb = openpyxl.load_workbook(output_file_path)
wb.save(output_file_path)
return True
except Exception as e:
messagebox.showerror('Error', str(e))
return False
def 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:
# 读取整个文件内容
ciphertext = input_file.read().decode() # 将bytes类型转换为字符串类型
# 对密文进行流密码解密
plaintext = stream_cipher_decrypt(ciphertext, key)
# 将明文写入输出文件
output_file.write(plaintext.encode())
# 根据输出文件的扩展名选择保存方式
file_extension = os.path.splitext(output_file_path)[1]
if file_extension == '.docx':
#如果是.docx文件,则使用python-docx库保存
doc = docx.Document(output_file_path)
doc.save(output_file_path)
elif file_extension == '.xlsx':
#如果是.xlsx文件,则使用openpyxl库保存
wb = openpyxl.load_workbook(output_file_path)
wb.save(output_file_path)
return True
except Exception as e:
messagebox.showerror('Error', str(e))
return False
修改后即可正常加密解密文件。
运行程序
- 将代码保存为
.py文件。 - 确保安装了必要的库:
tkinter、docx、openpyxl。 - 运行
.py文件。
注意事项
- 本代码示例使用了简单的流密码算法,安全性较低,不建议用于实际的敏感数据加密。
- 请根据实际需求修改代码,例如修改密钥长度、加密算法等。
- 在使用此代码进行文件加密解密时,请务必妥善保管密钥,避免密钥泄露导致数据丢失。
原文地址: https://www.cveoy.top/t/topic/oUZ1 著作权归作者所有。请勿转载和采集!