效果展示
代码介绍
该代码采用了对称加密的 Fernet 方法。Fernet 使用 AES 加密算法和 HMAC 进行数据完整性检查。加密和解密使用同一密钥,保证数据的安全性和完整性。生成的密钥会在应用运行时自动生成并用于加密和解密文本。
1.主窗口 (EncryptionApp 类):
1.1继承了 tk.Tk,表示应用的主窗口。
1.2self.title(“Panda”):设置窗口的标题为 “Panda”。
1.3self.geometry(“400x600”):设置窗口的大小为 400x600 像素。
1.4self.iconbitmap(‘logo.ico’):设置窗口图标为 ‘logo.ico’。
1.5self.key:生成了一个加密密钥,通过 Fernet.generate_key()。
1.6self.cipher_suite:创建了一个加密套件,基于生成的密钥,负责加密和解密数据。
2.界面布局 (create_widgets 方法):
2.1self.encrypt_frame 和 self.decrypt_frame:分别是加密功能和解密功能的界面区域,使用 tk.Frame 创建。
2.2tk.Label:用于显示提示文本,如“输入待加密文本”、“加密后的文本”等。
2.3tk.Text:用于用户输入和显示加密/解密结果的多行文本框。
2.4tk.Button:提供了“加密”和“解密”两个按钮,分别用于触发加密和解密操作。
3.加密文本 (encrypt_text 方法):
3.1获取用户输入的明文,通过 self.input_text_encrypt.get() 方法从文本框中读取内容。
3.2如果输入为空,使用 messagebox.showwarning 弹出一个警告窗口,提醒用户输入文本。
3.3使用 self.cipher_suite.encrypt() 对输入的明文进行加密,将其转换为密文。
3.4将加密后的密文显示在界面的“加密后的文本”区域。
4.解密文本 (decrypt_text 方法):
4.1从“输入待解密文本”的文本框中获取密文。
4.2如果输入为空,使用 messagebox.showwarning 提示用户输入文本。
4.3使用 self.cipher_suite.decrypt() 进行解密,将密文转换为明文。
4.4如果解密过程中发生错误(如密文格式错误),则捕获异常并使用 messagebox.showerror 显示错误消息。
4.5解密后的明文显示在界面的“解密后的文本”区域。
部分源码
#源码公众号PandaYY私信1003
import tkinter as tk
from tkinter import messagebox
from cryptography.fernet import Fernet
class EncryptionApp(tk.Tk):
def __init__(self):
super().__init__()
self.title("Panda")
self.geometry("400x600")
# 设置窗口图标
self.iconbitmap('logo.ico')
# 生成一个加密密钥
self.key = Fernet.generate_key()
self.cipher_suite = Fernet(self.key)
# 创建界面组件
self.create_widgets()
def create_widgets(self):
# 加密功能区域
self.encrypt_frame = tk.Frame(self)
self.encrypt_frame.pack(pady=10)
self.input_label_encrypt = tk.Label(self.encrypt_frame, text="输入待加密文本:")
self.input_label_encrypt.pack(pady=5)
self.input_text_encrypt = tk.Text(self.encrypt_frame, height=5, width=60)
self.input_text_encrypt.pack(pady=5)
self.encrypt_button = tk.Button(self.encrypt_frame, text="加密", command=self.encrypt_text)
self.encrypt_button.pack(pady=10)
self.encrypted_label = tk.Label(self.encrypt_frame, text="加密后的文本:")
self.encrypted_label.pack(pady=5)
self.encrypted_text = tk.Text(self.encrypt_frame, height=5, width=60)
self.encrypted_text.pack(pady=5)
# 解密功能区域
self.decrypt_frame = tk.Frame(self)
self.decrypt_frame.pack(pady=10)
self.input_label_decrypt = tk.Label(self.decrypt_frame, text="输入待解密文本:")
self.input_label_decrypt.pack(pady=5)
self.input_text_decrypt = tk.Text(self.decrypt_frame, height=5, width=60)
self.input_text_decrypt.pack(pady=5)
self.decrypt_button = tk.Button(self.decrypt_frame, text="解密", command=self.decrypt_text)
self.decrypt_button.pack(pady=5)
self.decrypted_label = tk.Label(self.decrypt_frame, text="解密后的文本:")
self.decrypted_label.pack(pady=5)
self.decrypted_text = tk.Text(self.decrypt_frame, height=5, width=60)
self.decrypted_text.pack(pady=5)