Programming

"The only way to learn a new programming language is by writing programs in it." - Dennis Ritchie

Raspberry Pi

“Genius is one percent inspiration and ninety-nine percent perspiration.” -Thomas Edison

Artificial Intelligence

“The pace of progress in artificial intelligence (I’m not referring to narrow AI) is incredibly fast. Unless you have direct exposure to groups like Deepmind, you have no idea how fast—it is growing at a pace close to exponential. The risk of something seriously dangerous happening is in the five-year time frame. 10 years at most.” —Elon Musk wrote in a comment on Edge.org

Electronics

“The five essential entrepreneurial skills for success are concentration, discrimination, organisation, innovation and communication.” -Michael Faraday

Crypto Currency

"Blockchain is the tech. Bitcoin is merely the first mainstream manifestation of its potential." – Marc Kenigsberg

20 Feb 2021

Simple Message Encrypter - Python Tkinter project

 Introduction

This project is aimed at making a Simple Message Encrypter using Python Tkinter. The application will be using a simple Symmetric Key algorithm.  Symmetric key algorithms are algorithms for which we use the same cryptographic keys for both encryption of plaintext and decryption of ciphertext (ie. we should use the same password, which the sender used at the time of encryption, for retrieving the message back to its original form). 

Pre-requisites

  • Basic knowledge of python
  • Understanding of tkinter

Project Demo Image




Final Output



Programming

The first step of creating application, is to create a folder for our program. Inside that folder, create a python file(.py extension). Open the python file in any text editor or any python IDE. 
The program begins by importing the tkinter module and defining the main window for the application.
import tkinter
root = tkinter.Tk()
root.title("Message Encrypter")
root.iconbitmap("resources/icons/encrypter.ico")

root.mainloop()

  • Import the Tkinter module, for making the GUI for the application. All we need to do, inorder to use Tkinter is a single import statement
  • initialize an instance of tkinter named "root". You can use your own specific names for this.
  • specify a title for our "root" window.
  • specify the icon. This icon will appear on the top left corner of our application. Even if you didn't specify anything, tkinter will give a default icon.
  • tkinter works by continuously looping through the code, which is specified by the mainloop(). If you forget to mention this line, your program will run without any error. But you will not be able to see it, since it will execute and close, within a fraction of second. If you run the code(at this instance), the application window will look like this. You can see the title of the application and the icon.

Make sure that you have specified the path of the icon (.ico file) correctly.
Get the icon used by me: Get Icon
If you would like to use a different icon, feel free to download an icon from any trusted source. Now its the time to define our frames and other widgets for the application. You must insert the code before the line "root.mainloop()" 
#Defining frames
input_frame = tkinter.Frame(root)
button_frame = tkinter.Frame(root,bg=button_frame_color)
input_frame.pack()
button_frame.pack(fill=BOTH,expand=True)

#Defining widgets for frames
input_data = tkinter.Entry(input_frame,width=80)
output_data = tkinter.Label(input_frame,text="Your output will appear here",bg=output_bg,fg=button_color,width=50,wraplength=200)
copy_button = tkinter.Button(input_frame,text="Copy",bg=button_color)
passwd_label = tkinter.Button(button_frame,text="Password",bg=button_frame_color,borderwidth=0)
passwd_data = tkinter.Entry(button_frame)
encrypt_button = tkinter.Button(button_frame,text="Encrypt",bg=button_color)
decrypt_button = tkinter.Button(button_frame,text="Decrypt",bg=button_color)

input_data.grid(row=0,column=0,columnspan=2,padx=10,pady=10,ipady=50)
output_data.grid(row=1,column=0,padx=10,pady=10,ipady=40,sticky="we")
copy_button.grid(row=1,column=1,pady=10,ipady=10,ipadx=20,padx=(0,10))
passwd_label.grid(row=0,column=0,pady=10,padx=(100,0),ipadx=20,ipady=10)
passwd_data.grid(row=0,column=1,pady=10,padx=(0,10),ipadx=50,ipady=10)
encrypt_button.grid(row=1,column=0,pady=10,padx=(80,0),ipadx=40,ipady=10)
decrypt_button.grid(row=1,column=1,pady=20,ipadx=40,ipady=10)


Our application is mainly divided into two frames: an input frame and  a button frame. The button frame is the gray portion and the input frame is the upper white region. 
  • Define two Frames for the application
  • Place it on to the root window, using the pack() method.
  • Input frame will have message entry region, output region and a copy button.
    • Define an Entry widget (named "input_data") to get the message from user.
    • Place it on the input frame using grid().
    • Define a display region, for outputting the result after processing, using a Label widget from tkinter. Wraplength specifies the length of the line after which a new line character is to be inserted.
    • Place a button widget for copying the content after encrypting/decrypting. Th efunction to be performed while clicking the button will be described below.
  • Button frame will have two buttons : one for encrypting and other for decrypting the message, along with an entry widget for getting the password from the user.
This will give you the basic layout for the application. The layout should look like the below image.

Now, as the layout is over, we should focus our mind to the functioning of the application. Each and every "Buttons" should be attached with a specific function, so that the function will run, once we click on the button. 
expected_char="qazwsxedcrfvtgbyhnujmikolp!@#$%^&*()1234567890POIUYTREWQASDFGHJKLMNBVCXZ~`<,>.?/:;'[{]}+=_-| "
expected_char+='"'
Our application is focused on a simple Symmetric Key Encryption algorithm. Symmentric Key Encryption means that the same Key (Password) which is used at the time of encryption, is needed for decrypting the message. 
Shift cipher concept is implemented here. In shift cipher: 
Cipher text = (Plain text + Password) mod <number of characters>
Inorder to include almost all the characters, that we use normally, I have added a string variable named "expected_char", which contains 94 different characters.
def encrypt():
    cipher_text=''
    plain_text=input_data.get()

    if passwd_data.get()!='':
        passwd=int(passwd_data.get())
        for i in plain_text:
            index=expected_char.find(i)
            updated_index=(index+passwd)%94
            cipher_text+=expected_char[updated_index]
        output_data.config(text=cipher_text)
        #input_data.delete(0,END)
    else:
        messagebox.showerror("Invalid Password","You must enter a password")
For encrypting purpose, we defined a function named encrypt. In-order to store the store the result, we initialized a variable named "cipher_text". It is defined as a local variable, so that we can use the same name in the decrypt function. Get the user input from the Entry widget and store it to the variable "plain_text". For encryption, a password id required. If the user fails to provide a password, the application will throw up an error message. We should update the output Label widget to display the encrypted message.
def decrypt(): 
    plain_text=''
    cipher_text=input_data.get()
    
    if passwd_data.get()!='':
        depasswd=int(passwd_data.get())
        for i in cipher_text:
            new_index=expected_char.find(i)
            new_updated_index=(new_index-depasswd)%94
            plain_text+=expected_char[new_updated_index]
        output_data.config(text=plain_text)
        #input_data.delete(0,END)
    else:
        messagebox.showerror("Invalid Password","You must enter a password inorder to decrypt the message")
Decrypt function will also do the same initial steps of retrieving the user input and initializing an empty string variable. Decryption is based on the formula:
Plain text = (Cipher text - Password) mod <number of characters>
We should update the output label to display the decrypted message.
def copy_data():
    pyperclip.copy(output_data['text'])
Copy_data function will be used to copy the result from the output Label widget, so that the user can send it through any other messaging platform like WhatsApp, Instagram, Snapchat, Twitter, etc.. Copying is done with the help of "pyperclip" module. Add this codes before the section which defines the frames. Link your functions with the appropriate buttons. 
Now your application is completely functional. 

Complete Source Code

GitHub: source code

'''
    program: Simple Message Encrypter
    author : akr
    github : a-k-r-a-k-r
'''

#import necessary modules
import tkinter
import pyperclip
from tkinter import DISABLED,messagebox,BOTH,END


#Defining root window
root=tkinter.Tk()
root.title("Message Encrypter")
root.iconbitmap("resources/icons/encrypter.ico")


#mostly used characters
expected_char="qazwsxedcrfvtgbyhnujmikolp!@#$%^&*()1234567890POIUYTREWQASDFGHJKLMNBVCXZ~`<,>.?/:;'[{]}+=_-| "
expected_char+='"'


#colors
button_frame_color="grey"
button_color="green"
output_bg="black"


#Defining functions
def encrypt():
    cipher_text=''
    plain_text=input_data.get()

    if passwd_data.get()!='':
        passwd=int(passwd_data.get())
        for i in plain_text:
            index=expected_char.find(i)
            updated_index=(index+passwd)%94
            cipher_text+=expected_char[updated_index]
        output_data.config(text=cipher_text)
        #input_data.delete(0,END)
    else:
        messagebox.showerror("Invalid Password","You must enter a password")


def decrypt(): 
    plain_text=''
    cipher_text=input_data.get()
    
    if passwd_data.get()!='':
        depasswd=int(passwd_data.get())
        for i in cipher_text:
            new_index=expected_char.find(i)
            new_updated_index=(new_index-depasswd)%94
            plain_text+=expected_char[new_updated_index]
        output_data.config(text=plain_text)
        #input_data.delete(0,END)
    else:
        messagebox.showerror("Invalid Password","You must enter a password inorder to decrypt the message")


def copy_data():
    pyperclip.copy(output_data['text'])


#Defining frames
input_frame=tkinter.Frame(root)
button_frame=tkinter.Frame(root,bg=button_frame_color)
input_frame.pack()
button_frame.pack(fill=BOTH,expand=True)

#Defining widgets for frames
input_data=tkinter.Entry(input_frame,width=80)
output_data=tkinter.Label(input_frame,text="Your output will appear here",bg=output_bg,fg=button_color,width=50,wraplength=200)
copy_button=tkinter.Button(input_frame,text="Copy",bg=button_color,command=copy_data)
passwd_label=tkinter.Button(button_frame,text="Password",bg=button_frame_color,borderwidth=0)
passwd_data=tkinter.Entry(button_frame)
encrypt_button=tkinter.Button(button_frame,text="Encrypt",bg=button_color,command=encrypt)
decrypt_button=tkinter.Button(button_frame,text="Decrypt",bg=button_color,command=decrypt)

input_data.grid(row=0,column=0,columnspan=2,padx=10,pady=10,ipady=50)
output_data.grid(row=1,column=0,padx=10,pady=10,ipady=40,sticky="we")
copy_button.grid(row=1,column=1,pady=10,ipady=10,ipadx=20,padx=(0,10))
passwd_label.grid(row=0,column=0,pady=10,padx=(100,0),ipadx=20,ipady=10)
passwd_data.grid(row=0,column=1,pady=10,padx=(0,10),ipadx=50,ipady=10)
encrypt_button.grid(row=1,column=0,pady=10,padx=(80,0),ipadx=40,ipady=10)
decrypt_button.grid(row=1,column=1,pady=20,ipadx=40,ipady=10)


root.mainloop()


Stand-alone Executable

In-order to run the application from your Window's desktop, just by clicking the icon, you will need to convert the program to a standalone executable. To achieve this 
pip install auto-py-to-exe

Open "auto-py-to-exe" by typing "auto-py-to-exe" in command prompt or in PowerShell. GUI for the same will appear.

  • Click on the "Browse" button and choose the ".py" file for the program.
  • Choose "One Directory". You can also choose to go with "One File". But in most cases, it will give errors. 
  • Choose to create Window Based instead of Console based
  • In the Icon field, browse the ".ico" file (this will appear on the exe file as the icon)
  • Add the Additional files. Since we have our icon in the resources folder, add the folder, using "Add Folder" button. This icon will appear on the application window's top left corner.
  • Now click on convert
  • Once complete, open the output folder and find the ".exe" file.
  • Make a shortcut of it and send it to desktop, for easy access.

Contributions

Feel free to contribute to the GitHub repository. Happy Hacking. If you have any weird ideas, comment below. Let's make it a reality.
                                                                                                      -akr