Programmin-in-Python

GUI Program for AES Encryption and Decryption

Dec 30th, 2020 (edited)
842
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 15.46 KB | None | 0 0
  1. #This Program Uses the Cipher-Block Chaining(CBC) mode of AES
  2. #Thus the Messages/data in a file that are not a block of 16 bytes shall be padded...
  3. #All Fields are Compulsory...
  4.  
  5. #It requires either the 'pycrypto' or 'pycryptodome' module
  6. #For More Projects and Programs, Check out my GitHub : https://github.com/Programmin-in-Python
  7.  
  8. import tkinter as tk
  9. from tkinter import ttk
  10. from tkinter import filedialog as fd
  11. from tkinter import messagebox as mb
  12. from Crypto.Cipher import AES
  13. from hashlib import sha256
  14. from ast import literal_eval
  15. from chardet import detect as dt
  16.  
  17. def encryption(type, root1):
  18.     root1.destroy()
  19.  
  20.     root = tk.Tk()
  21.     root.title("AES Encryption and Decryption")
  22.     root.geometry('{}x{}+0+0'.format(*root.maxsize()))
  23.     root.resizable(False, False)   
  24.     root.group()   
  25.  
  26.     #============================= Variables ====================================
  27.     global filenameE, inp_strE, keyE, IVe, encodingE
  28.     global filenameD, inp_strD, keyD, IVd, encodingD
  29.  
  30.     filenameE = tk.StringVar(root)
  31.     inp_strE = tk.StringVar(root)
  32.     encodingE = tk.StringVar(root)
  33.     keyE = tk.StringVar(root)
  34.     IVe = tk.StringVar(root)   
  35.  
  36.     filenameD = tk.StringVar(root)
  37.     encodingD = tk.StringVar(root) 
  38.     keyD = tk.StringVar(root)
  39.     IVd = tk.StringVar(root)
  40.  
  41.     encodings = ('ascii', 'big5', 'big5hkscs', 'cp037', 'cp273', 'cp424', 'cp437', 'cp500', 'cp720',
  42.                 'cp737', 'cp775', 'cp850', 'cp852', 'cp855', 'cp856', 'cp857', 'cp858', 'cp860', 'cp861',
  43.                 'cp862', 'cp863', 'cp864', 'cp865', 'cp866', 'cp869', 'cp874', 'cp875', 'cp932', 'cp949',
  44.                 'cp950','cp1006', 'cp1026', 'cp1125', 'cp1140', 'cp1250', 'cp1251', 'cp1252', 'cp1253',
  45.                 'cp1254', 'cp1255', 'cp1256', 'cp1257', 'cp1258', 'cp65001', 'euc_jp', 'euc_jis_2004',
  46.                 'euc_jisx0213', 'euc_kr', 'gb2312', 'gbk', 'gb18030', 'hz', 'iso2022_jp', 'iso2022_jp_1',
  47.                 'iso2022_jp_2', 'iso2022_jp_2004', 'iso2022_jp_3', 'iso2022_jp_ext', 'iso2022_kr',
  48.                 'latin_1','iso8859_2', 'iso8859_3', 'iso8859_4', 'iso8859_5', 'iso8859_6', 'iso8859_7',
  49.                 'iso8859_8', 'iso8859_9', 'iso8859_10', 'iso8859_11', 'iso8859_13', 'iso8859_14',
  50.                 'iso8859_15', 'iso8859_16', 'johab', 'koi8_r', 'koi8_t', 'koi8_u', 'kz1048', 'mac_cyrillic',
  51.                 'mac_greek', 'mac_iceland', 'mac_latin2', 'mac_roman', 'mac_turkish', 'ptcp154', 'shift_jis',
  52.                 'shift_jis_2004', 'shift_jisx0213','utf_32', 'utf_32_be', 'utf_32_le', 'utf_16', 'utf_16_be',
  53.                 'utf_16_le', 'utf_7', 'utf_8', 'utf_8_sig')
  54.  
  55.     #============================= Function to Choose File ======================
  56.     def chooseFile(file_type):
  57.         filename = fd.askopenfilename(title="AES Encryption and Decryption")
  58.         if file_type == "encrypt":
  59.             filenameE.set(filename)
  60.         else:
  61.             filenameD.set(filename)
  62.  
  63.     #============================= Label Frames =================================
  64.     Mainframe = tk.Frame(root)
  65.     Mainframe.grid()
  66.  
  67.     Tops = tk.Frame(Mainframe , bd = 10 , relief = 'ridge')
  68.     Tops.pack(side = 'top')
  69.  
  70.     lblTitle = tk.Label(Tops , width = 34 , font = ('arial' , 40 , 'bold') ,
  71.                                 text = 'AES Encryption and Decryption' , justify = 'center')
  72.     lblTitle.grid(padx = 150)
  73.  
  74.     Membername = tk.LabelFrame(Mainframe , bd = 10 , width = 600 , height = 612 ,
  75.                                 font = ('Times New Roman' , 14 , 'bold') , text = 'Encryption' , relief = 'ridge')
  76.     Membername.pack(padx = 38 , side = 'left')
  77.     Membername.grid_propagate(False)
  78.  
  79.     Membername2 = tk.LabelFrame(Mainframe , bd = 10 , width = 600 , height = 612 ,
  80.                                 font = ('Times New Roman' , 14 , 'bold') , text = 'Decryption' , relief = 'ridge')
  81.     Membername2.pack(padx = 38 , side = 'right')
  82.     Membername2.grid_propagate(False)
  83.  
  84.     #============================== Widgets for Encryption ===========================================
  85.     if type == "text":
  86.         lblstr = tk.Label(Membername , font = ('arial', 16),
  87.                                     text = 'Normal Text String' , bd = 7)
  88.         lblstr.grid(row = 0 , column = 0)
  89.         txtstr = tk.Entry(Membername , font = ('arial', 17),
  90.                                 textvariable = inp_strE, bd = 7, insertwidth = 2)
  91.         txtstr.grid(row=0,column=1)
  92.     else:
  93.         lblstr = tk.Label(Membername , font = ('arial', 16),
  94.                                     text = 'Choose Normal File' , bd = 7)
  95.         lblstr.grid(row = 0 , column = 0)
  96.         txtstr = tk.Entry(Membername , font = ('arial', 17),
  97.                                 textvariable = filenameE, bd = 7, insertwidth = 2, state="disabled")
  98.         txtstr.grid(row=0,column=1)
  99.  
  100.         btnChoose = tk.Button(Membername, font = ('arial', 16), bd=7, text = 'Choose File', command = lambda : chooseFile("encrypt"))
  101.         btnChoose.grid(row=1, column=1)
  102.  
  103.     lblenc = tk.Label(Membername , font = ('arial', 16),
  104.                                 text = 'Encoding Scheme' , bd = 7)
  105.     lblenc.grid(row = 2 , column = 0)
  106.     txtenc = ttk.Combobox(Membername, font = ('arial', 16), textvariable = encodingE)
  107.     txtenc['values'] = encodings
  108.     txtenc.current(0)
  109.     txtenc.grid(row=2,column=1)
  110.  
  111.     lblkey = tk.Label(Membername , font = ('arial', 16),
  112.                                 text = 'Encryption Key' , bd = 7)
  113.     lblkey.grid(row = 3 , column = 0)
  114.     txtkey = tk.Entry(Membername , font = ('arial', 17),
  115.                             textvariable = keyE, bd = 7, insertwidth = 2, show="*")
  116.     txtkey.grid(row=3,column=1)
  117.  
  118.     lblIV = tk.Label(Membername , font = ('arial', 16),
  119.                                 text = 'Initialization Vector' , bd = 7)
  120.     lblIV.grid(row = 4 , column = 0)
  121.     txtIV = tk.Entry(Membername , font = ('arial', 17),
  122.                             textvariable = IVe, bd = 7, insertwidth = 2)
  123.     txtIV.grid(row=4,column=1)
  124.  
  125.     lblResultE = tk.Label(Membername , font = ('arial', 16) , \
  126.                                 text = '\n\n\n\nResult' , bd = 7)
  127.     lblResultE.grid(row = 6 , column = 0 , sticky = 'n')
  128.     txtResultE = tk.Text(Membername , width = 25 , height = 10 , font = ('arial', 16, "bold"),
  129.                         foreground='black', background='white', state='disabled')
  130.     txtResultE.grid(row = 6 , column = 1)  
  131.  
  132.     #=============================== Widgets for Decryption ==========================
  133.     if type == "text":
  134.         lblstr = tk.Label(Membername2 , font = ('arial', 16),
  135.                                     text = 'AES Encrypted String' , bd = 7)
  136.         lblstr.grid(row = 0 , column = 0)
  137.         txtstr1 = tk.Entry(Membername2 , font = ('arial', 17), bd = 7, insertwidth = 2)
  138.         txtstr1.grid(row=0,column=1)
  139.     else:
  140.         lblstr = tk.Label(Membername2 , font = ('arial', 16),
  141.                                     text = 'Choose Encrypted File' , bd = 7)
  142.         lblstr.grid(row = 0 , column = 0)
  143.         txtstr1 = tk.Entry(Membername2 , font = ('arial', 17),
  144.                                 textvariable = filenameD, bd = 7, insertwidth = 2, state="disabled")
  145.         txtstr1.grid(row=0,column=1)
  146.  
  147.         btnChoose1 = tk.Button(Membername2, font = ('arial', 16), bd=7, text = 'Choose File', command = lambda : chooseFile("decrypt"))
  148.         btnChoose1.grid(row=1, column=1)
  149.  
  150.     lblenc1 = tk.Label(Membername2 , font = ('arial', 16),
  151.                                 text = 'Encoding Scheme' , bd = 7)
  152.     lblenc1.grid(row = 2 , column = 0)
  153.     txtenc1 = ttk.Combobox(Membername2, font = ('arial', 16), textvariable = encodingD)
  154.     txtenc1['values'] = encodings
  155.     txtenc1.current(0)
  156.     txtenc1.grid(row=2,column=1)
  157.  
  158.     lblkey = tk.Label(Membername2 , font = ('arial', 16),
  159.                                 text = 'Encryption Key' , bd = 7)
  160.     lblkey.grid(row = 3 , column = 0)
  161.     txtkey1 = tk.Entry(Membername2 , font = ('arial', 17),
  162.                             textvariable = keyD, bd = 7, insertwidth = 2, show="*")
  163.     txtkey1.grid(row=3,column=1)
  164.  
  165.     lblIV = tk.Label(Membername2 , font = ('arial', 16),
  166.                                 text = 'Initialization Vector' , bd = 7)
  167.     lblIV.grid(row = 4 , column = 0)
  168.     txtIV1 = tk.Entry(Membername2 , font = ('arial', 17),
  169.                             textvariable = IVd, bd = 7, insertwidth = 2)
  170.     txtIV1.grid(row=4,column=1)
  171.  
  172.     lblResultD = tk.Label(Membername2 , font = ('arial', 16) , \
  173.                                 text = '\n\n\n\nResult' , bd = 7)
  174.     lblResultD.grid(row = 6 , column = 0 , sticky = 'n')
  175.     txtResultD = tk.Text(Membername2 , width = 25 , height = 10 , font = ('arial', 16, "bold"),
  176.                         foreground='black', background='white', state='disabled')
  177.     txtResultD.grid(row = 6 , column = 1)
  178.  
  179.     #============================== Function to Encrypt and Decrypt =====================
  180.     def pad_msg(msg):
  181.  
  182.         if isinstance(msg, bytes):
  183.             while bool(len(msg) % 16):
  184.                 msg += b'0'
  185.         elif isinstance(msg, str):
  186.             while bool(len(msg) % 16):
  187.                 msg += " " 
  188.  
  189.         return msg
  190.  
  191.     def encrypt(enc_type):
  192.         global filenameE, inp_strE, keyE, IVe
  193.         global filenameD, inp_strD, keyD, IVd
  194.  
  195.  
  196.  
  197.         if not (any(filenameE.get()) or any(filenameD.get()) or any(inp_strE.get()) or any(txtstr1.get())):
  198.             txtstr.config(bg='red', fg='white')
  199.             txtstr1.config(bg='red', fg='white')
  200.             mb.showerror("AES Encryption and Decryption", "You've left both the Input Field Empty!!!\nAll Fields of a single sub-column are Compulsory...")
  201.            
  202.         elif not (any(keyE.get()) or any(keyD.get())):
  203.             txtkey.config(bg='red', fg='white')
  204.             txtkey1.config(bg='red', fg='white')
  205.             mb.showerror("AES Encryption and Decryption", "You've left both the 'Encryption Key' Field Empty!!!\nAll Fields of a single sub-column are Compulsory...")
  206.            
  207.         elif not (any(IVe.get()) or any(IVd.get())):
  208.             txtIV.config(bg='red', fg='white')
  209.             txtIV1.config(bg='red', fg='white')
  210.             mb.showerror("AES Encryption and Decryption", "You've left both the 'Initialization Vector' Field Empty!!!\nAll Fields of a single sub-column are Compulsory...")
  211.            
  212.         else :
  213.             if type == "text":
  214.                 if enc_type == "encrypt":
  215.                     password = keyE.get().encode()
  216.                     key = sha256(password).digest()
  217.                     mode = AES.MODE_CBC
  218.  
  219.                     if any(IVe.get()):
  220.                         IV = IVe.get().encode()
  221.                         cipher = AES.new(key, mode, IV)
  222.  
  223.                     else:
  224.                         txtIV.config(bg='red', fg='white')
  225.                         mb.showerror("AES Encryption", "You've left the 'Initialization Vector' Field Empty!!!\nAll Fields are Compulsory...")
  226.                         cipher = AES.new(key, mode)
  227.  
  228.                     message = pad_msg(inp_strE.get())
  229.  
  230.                     if not any(encodingE.get()):
  231.                         mb.showinfo("AES Encryption", "You haven't selected any Encoding Scheme\nThe Default Scheme 'ascii' will be considered...")
  232.                         enc_msg = cipher.encrypt(message.encode())
  233.                     else:
  234.                         enc_msg = cipher.encrypt(message.encode(encodingE.get()))
  235.  
  236.                     txtResultE.config(state="normal")
  237.                     txtResultE.delete('1.0', 'end')
  238.                     txtResultE.insert('1.0', rf'{enc_msg}')
  239.  
  240.                 else:
  241.                     str_input = literal_eval(rf'{txtstr1.get()}')
  242.  
  243.                     password2 = keyD.get().encode()
  244.                     key2 = sha256(password2).digest()
  245.                     mode2 = AES.MODE_CBC
  246.  
  247.                     if any(IVd.get()):
  248.                         IV2 = IVd.get().encode()
  249.                         cipher2 = AES.new(key2, mode2, IV2)
  250.  
  251.                     else:
  252.                         txtIV1.config(bg='red', fg='white')
  253.                         mb.showerror("AES Decryption", "You've left the 'Initialization Vector' Field Empty!!!\nAll Fields are Compulsory...")
  254.                         cipher2 = AES.new(key2, mode2)         
  255.                    
  256.                     dec_msg = cipher2.decrypt(str_input)       
  257.  
  258.                     txtResultD.config(state="normal")
  259.                     txtResultD.delete('1.0', 'end')
  260.  
  261.                     if not any(encodingD.get()):
  262.                         enc_scheme = dt(dec_msg)['encoding']
  263.                         mb.showinfo("AES Encryption", f"You haven't selected any Encoding Scheme\nIt has been detected that the string has been encoded with {enc_scheme}")
  264.                         txtResultD.insert('1.0', dec_msg.decode(enc_scheme).strip())
  265.                     else:
  266.                         txtResultD.insert('1.0', dec_msg.decode(encodingD.get()).strip())
  267.  
  268.             else:
  269.                 if enc_type == "encrypt":
  270.  
  271.                     with open(filenameE.get()) as file:
  272.                         data = file.read()
  273.  
  274.                         password = keyE.get().encode()
  275.                         key = sha256(password).digest()
  276.                         mode = AES.MODE_CBC
  277.  
  278.                         if any(IVe.get()):
  279.                             IV = IVe.get().encode()
  280.                             cipher = AES.new(key, mode, IV)
  281.  
  282.                         else:
  283.                             txtIV.config(bg='red', fg='white')
  284.                             mb.showerror("AES Encryption", "You've left the 'Initialization Vector' Field Empty!!!\nAll Fields are Compulsory...")
  285.                             cipher = AES.new(key, mode)
  286.  
  287.                         message = pad_msg(data)
  288.  
  289.                         if not any(encodingE.get()):
  290.                             mb.showinfo("AES Encryption", "You haven't selected any Encoding Scheme\nThe Default Scheme 'ascii' will be considered...")
  291.                             enc_msg = cipher.encrypt(message.encode())
  292.                         else:
  293.                             enc_msg = cipher.encrypt(message.encode(encodingE.get()))
  294.  
  295.                     with open("Encrypted.dat", 'wb') as res_file:
  296.                         res_file.write(enc_msg)
  297.  
  298.                     mb.showinfo("AES Encryption", "The Result has been SUCCESSFULLY Written to a File named 'Encrypted.dat'...")
  299.  
  300.                     txtResultE.config(state="normal")
  301.                     txtResultE.delete('1.0', 'end')
  302.                     txtResultE.insert('1.0', "The Result has been SUCCESSFULLY Written to a File named 'Encrypted.dat'...")
  303.                     txtResultE.config(state="disabled")
  304.  
  305.                 else:
  306.                     with open(filenameD.get(), 'rb') as file:
  307.                         data = file.read()
  308.  
  309.                         password2 = keyD.get().encode()
  310.                         key2 = sha256(password2).digest()
  311.                         mode2 = AES.MODE_CBC
  312.  
  313.                         if any(IVd.get()):
  314.                             IV2 = IVd.get().encode()
  315.                             cipher2 = AES.new(key2, mode2, IV2)
  316.  
  317.                         else:
  318.                             txtIV1.config(bg='red', fg='white')
  319.                             mb.showerror("AES Decryption", "You've left the 'Initialization Vector' Field Empty!!!\nAll Fields are Compulsory...")
  320.                             cipher2 = AES.new(key2, mode2)
  321.                        
  322.                         dec_msg = cipher2.decrypt(data)
  323.  
  324.                     if not any(encodingD.get()):
  325.                         enc_scheme = dt(dec_msg)['encoding']
  326.                         mb.showinfo("AES Encryption", f"You haven't selected any Encoding Scheme\nIt has been detected that the string has been encoded with {enc_scheme}")
  327.                     else:
  328.                         enc_scheme = encodingD.get()
  329.  
  330.                     with open("Decrypted.txt", "w") as res_file:
  331.                         res_file.write(dec_msg.decode(enc_scheme).strip())
  332.  
  333.                     mb.showinfo("AES Decryption", "The Result has been SUCCESSFULLY Written to a File named 'Decrypted.dat'...")
  334.  
  335.                     txtResultD.config(state="normal")
  336.                     txtResultD.delete('1.0', 'end')
  337.                     txtResultD.insert('1.0', "The Result has been SUCCESSFULLY Written to a File named 'Decrypted.txt'...")
  338.                     txtResultD.config(state="disabled")
  339.  
  340.     btnEncrypt = tk.Button(Membername, font=('arial', 16, 'bold'), text='Encrypt', command = lambda : encrypt("encrypt") , bd = 7)
  341.     btnEncrypt.grid(row = 10 , column = 1 , sticky = 'w')
  342.  
  343.     btnDecrypt = tk.Button(Membername2, font=('arial', 16, 'bold'), text='Decrypt', command = lambda : encrypt("decrypt") , bd = 7)
  344.     btnDecrypt.grid(row = 10 , column = 1 , sticky = 'w')
  345.  
  346.     mb.showwarning("AES Encryption and Decryption", "This Program Uses the Cipher-Block Chaining(CBC) mode of AES\nThus, all Fields are Compulsory...and\nMessages that are not a block of 16 bytes shall be padded...")
  347.  
  348.     root.mainloop()
  349.  
  350. def main():
  351.     root = tk.Tk()
  352.     root.title("AES Encryption and Decryption")
  353.     root.resizable(False, False)   
  354.     root.group()
  355.  
  356.     #============================= Buttons and Widgets ===========================
  357.     lbltitle = tk.Label(root , font = ('Times new Roman' , 24 , 'bold') ,
  358.                            text = '\t\t\tAES Encryption and Decryption')
  359.     lbltitle.grid(row = 0 , column = 0)
  360.  
  361.     lbltitle2 = tk.Label(root , font = ('Times new Roman' , 20 , 'bold') ,
  362.                            text = '\t\t\t\tChoose Any One...\n')
  363.     lbltitle2.grid(row = 1 , column = 0)
  364.  
  365.     btnFile = tk.Button(root, font=('arial', 16, 'bold'), text='Encrypt/Decrypt FILE', command = lambda : encryption("file", root) , bd = 7)
  366.     btnFile.grid(row = 2 , column = 0 , sticky = 'w')
  367.  
  368.     btnText = tk.Button(root, font=('arial', 16, 'bold'), text='Encrypt/Decrypt TEXT STRING', command = lambda : encryption("text", root), bd = 7)
  369.     btnText.grid(row=2 , column=1 , sticky = 'w')
  370.  
  371.     root.mainloop()
  372. main()
Advertisement
Add Comment
Please, Sign In to add comment