python aes加解密 有界面
时间: 2024-10-13 21:08:22 浏览: 39
在Python中,你可以使用`pycryptodome`库来进行AES(Advanced Encryption Standard)加密和解密操作,并结合`tkinter`或其他GUI库来创建一个简单的图形用户界面。下面是一个基本的例子:
首先,你需要安装所需的库:
```bash
pip install pycryptodome tkinter
```
然后,你可以编写一个简单的GUI程序,包含输入框、按钮以及显示结果的部分:
```python
import tkinter as tk
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from base64 import b64encode, b64decode
class AESApp(tk.Tk):
def __init__(self):
super().__init__()
self.title("AES 加解密")
# UI elements
self.text_input = tk.Entry(self)
self.text_input.pack()
self.button_encrypt = tk.Button(text="加密", command=self.encrypt)
self.button_encrypt.pack()
self.button_decrypt = tk.Button(text="解密", command=self.decrypt)
self.button_decrypt.pack()
self.result_text = tk.Label(self, text="")
self.result_text.pack()
def encrypt(self):
key = b'This is a secret key1234567890' # 用于AES的固定秘钥
iv = b'Initial vector' # 初始化向量,保证每次加密的结果不同
plaintext = self.text_input.get().encode('utf-8')
cipher = AES.new(key, AES.MODE_CBC, iv)
ciphertext = cipher.encrypt(pad(plaintext, AES.block_size))
encrypted_text = b64encode(cipher.iv + ciphertext).decode('utf-8')
self.result_text.config(text=f"Encrypted: {encrypted_text}")
def decrypt(self):
key = b'This is a secret key1234567890'
iv = b64decode(self.text_input.get()).split(b":")[0] # 解码并提取iv
try:
decoded = b64decode(self.text_input.get()[len(iv):])
cipher = AES.new(key, AES.MODE_CBC, iv)
decrypted_plaintext = unpad(cipher.decrypt(decoded), AES.block_size)
self.result_text.config(text=f"Decrypted: {decrypted_plaintext.decode('utf-8')}")
except Exception as e:
self.result_text.config(text=f"Error: {str(e)}")
if __name__ == "__main__":
app = AESApp()
app.mainloop()
```
在这个例子中,用户可以输入明文,选择加密或解密按钮,对应的加密或解密过程会通过`pycryptodome`完成,并在结果显示标签中展示结果。
阅读全文