'''
需求: 做一个带界面的AES加密解密小工具
1.支持选择加密方式:ECB,CBC,CTR,CFB,OFB
2.支持加密, 支持选择偏移量iv
3.支持解密, 支持选择便宜量iv
'''
from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex
import tkinter as tk
def add_to_16(text):
if len(text.encode('utf-8')) % 16:
add = 16 - (len(text.encode('utf-8')) % 16)
else:
add = 0
text = text + ('\0' * add)
return text.encode('utf-8')
def encrypt(text,key,iv):
key = key.encode('utf-8')
mode = AES.MODE_CBC
text = add_to_16(text)
cryptos = AES.new(key, mode, iv)
cipher_text = cryptos.encrypt(text)
return b2a_hex(cipher_text)
def decrypt(text,key,iv):
key = key.encode('utf-8')
mode = AES.MODE_CBC
cryptos = AES.new(key, mode, iv)
plain_text = cryptos.decrypt(a2b_hex(text))
return bytes.decode(plain_text).rstrip('\0')
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack()
self.create_widgets()
def create_widgets(self):
self.text1 = tk.Label(self,text='输入框:')
self.text1.pack()
self.text_input = tk.Entry(self,width=50)
self.text_input.pack()
self.text2 = tk.Label(self,text='密码框:')
self.text2.pack()
self.key_input = tk.Entry(self)
self.key_input.pack()
self.text3 = tk.Label(self,text='偏移框:')
self.text3.pack()
self.vi_input = tk.Entry(self)
self.vi_input.pack()
self.button_encrypt = tk.Button(self,text="加密")
self.button_encrypt["command"] = self.AES_encrypt
self.button_encrypt.pack(side="top")
self.button_decrypt = tk.Button(self,text="解密")
self.button_decrypt["command"] = self.AES_decrypt
self.button_decrypt.pack(side="top")
self.text4 = tk.Label(self,text='输出框:')
self.text4.pack()
self.output = tk.Entry(self,width=50)
self.output.pack()
def AES_encrypt(self):
self.output.select_clear()
text_input = self.text_input.get()
print(text_input)
key_input = self.key_input.get()
vi_input = self.vi_input.get()
output = encrypt(text_input,key_input,vi_input)
self.output.insert(0,output)
def AES_decrypt(self):
self.output.select_clear()
text_input = self.text_input.get()
key_input = self.key_input.get()
vi_input = self.vi_input.get()
output = decrypt(text_input,key_input,vi_input)
self.output.insert(0,output)
if __name__ == '__main__':
test_text = '12345'
print('加密前:',test_text)
e = encrypt(test_text,'1234567890123456','1234567890123456')
d = decrypt(e,'1234567890123456','1234567890123456')
print("加密后:", e)
print("解密后:", d)
root = tk.Tk()
app = Application(master=root)
app.mainloop()