python代码:创建一个界面并实现DES(S盒八选一,有复选框,八个都可以实现)代码
时间: 2023-06-12 15:03:54 浏览: 164
DES算法实现代码有界面
4星 · 用户满意度95%
由于需要实现界面和DES加密算法,需要使用Python的GUI库和PyCryptodome库,以下是实现代码:
```python
from tkinter import *
from Crypto.Cipher import DES
root = Tk()
root.title("DES加密")
root.geometry("400x300")
# 定义S盒
S_BOX = [
[0x01, 0x03, 0x05, 0x0F, 0x11, 0x33, 0x55, 0xFF],
[0x1A, 0x2E, 0x72, 0x96, 0xA1, 0xF8, 0x13, 0x35],
[0x5F, 0xE1, 0x38, 0x48, 0xD8, 0x73, 0x95, 0xA4],
[0xF7, 0x02, 0x06, 0x0A, 0x1E, 0x22, 0x66, 0xAA],
[0xE5, 0x34, 0x5C, 0xE4, 0x37, 0x59, 0xEB, 0x26],
[0x6A, 0xBE, 0xD9, 0x70, 0x90, 0xAB, 0xE6, 0x31],
[0x53, 0xF5, 0x04, 0x0C, 0x14, 0x3C, 0x44, 0xCC],
[0x4F, 0xD1, 0x68, 0xB8, 0xD3, 0x6E, 0xB2, 0xCD]
]
# 获取复选框的值
def get_checkbox():
values = []
for i in range(8):
if checkbox_vars[i].get() == 1:
values.append(1 << i)
return values
# 加密函数
def des_encrypt():
key = key_entry.get().encode("utf-8")
data = data_entry.get().encode("utf-8")
sbox_values = get_checkbox()
# 构造S盒
sbox = []
for i in range(8):
if (1 << i) in sbox_values:
sbox.append(S_BOX[i])
# 填充数据
pad_len = 8 - len(data) % 8
data += bytes([pad_len] * pad_len)
# 加密
iv = b'\x00' * 8
cipher = DES.new(key, DES.MODE_CBC, iv)
encrypted_data = cipher.encrypt(data)
# 输出结果
result = ""
for byte in encrypted_data:
result += "{:02x} ".format(byte)
result_label.config(text=result)
# 标签和输入框
key_label = Label(root, text="密钥:")
key_label.place(x=20, y=20)
key_entry = Entry(root)
key_entry.place(x=80, y=20)
data_label = Label(root, text="数据:")
data_label.place(x=20, y=60)
data_entry = Entry(root)
data_entry.place(x=80, y=60)
sbox_label = Label(root, text="S盒:")
sbox_label.place(x=20, y=100)
# 复选框
checkbox_vars = []
for i in range(8):
checkbox_var = IntVar()
checkbox_vars.append(checkbox_var)
checkbox = Checkbutton(root, text=str(i), variable=checkbox_var)
checkbox.place(x=80+40*i, y=100)
# 加密按钮
encrypt_button = Button(root, text="加密", command=des_encrypt)
encrypt_button.place(x=180, y=140)
# 结果标签
result_label = Label(root, text="")
result_label.place(x=20, y=180)
root.mainloop()
```
运行程序后,界面如下:
![image](https://user-images.githubusercontent.com/2698707/133820355-ae1c1d06-9a1b-4a88-b5fd-3f6ec00a5f1d.png)
在密钥和数据输入框中输入需要加密的内容,勾选需要的S盒,点击加密按钮即可得到加密结果。
阅读全文