Python is an increasingly popular coding language that offers a massive amount of creativity. By taking advantage of the simplified syntax of Python, new users can quickly get a grasp on how to start programming.
In my previous article, I explained how to get started in Python, and further explored the basics of coding within Python. By applying the knowledge gained in the previous article, along with the information presented within this new article, users will be able to create their very own Python applications.
Everything you need to know.
Before we start coding, there are a few things that you should be aware of before coding. Firstly, it is important to ensure that you have read my previous blog post: how to start coding in Python. And that you fully understand the information that was conveyed within that article. The topics covered within that article provide everything you need to know regarding this application and is a great starting point. Additionally, W3Schools is a great resource for learning coding languages, including Python.
Furthermore, I will be covering some more advanced features within Python, such as lists, reading/writing to a file, and encrypting/decrypting data.
What type of Python application are we coding?
I will be showing you how to create a simple password manager application using Python. To create this app, I will be using the PyCharm IDE, which you can install by following my previous article as a tutorial.
This password manager application will enable users to enter the software/website, the username for that software as well as the password, saving it to a secure file for you to refer to later. Confidential information, such as usernames or passwords, should always be encrypted. This encryption allows for increased security to ensure no unauthorized users take your passwords.
New Python Commands
There are a few new pieces of code we will have to discuss before diving into creating the application. Feel free to follow along by typing out the code segments into your PyCharm IDE to see the outputs.
The first of the new Python features I will be covering in this article is the lists command. In other programming languages, lists are often referred to as arrays. In Python, however, there is no such thing as arrays without having to download additional libraries. Instead, Python uses lists, which is essentially a collection of items.
To create a list of items, similar to how I will be creating them in the password manager application, enter the commands below:
vegetables = 'broccoli carrot cauliflower corn' veggieList = vegetables.split() print(veggieList) print(veggieList) print(veggieList) print(veggieList)
The above code will take the string vegetables, and splits the string into 4 separate strings within the list known as veggieList.
In the case of passwords, it is always important to keep them secure and keep them encrypted. In this application, I will be encrypting the passwords using a Caesar Cipher. The Caesar Cipher shifts each character in the string up in the alphabet based on a key.
To build our data encryption algorithm in Python, we will be using a function. Functions are blocks of code that only run when they are specifically called. This is great when trying to do massive operations, multiple times.
To create a function, type “def” followed by the name of the function and any input parameters within parentheses, as shown below.
def helloFunction(name): print("Hello there",name) helloFunction("Alfred")
Read/Write to a file
Reading and writing to files in Python is relatively simple. To create a new file, and write to the file, enter the commands below.
f = open("demo", "a") f.write("Now the file has more content!") f.close() #Always close file after using to prevent memory leaks f = open("demofile2.txt", "r") print(f.read())
In the ‘f = open(“demo”, “a”)’ statement, the “a” stands for append. This “a” can be replaced by “w” which will overwrite any existing data within that file, or with “x” which will create the empty file but will result in an error if the file already exists. The “r” option can be used if you only need to read the contents of the file.
Coding the application.
The first thing to do is to create a new project. Open up PyCharm and select File -> New Project. Choose a file directory on your computer where you would like to save the project and deselect the ‘main.py’ checkbox. After choosing all the correct settings, hit create and let PyCharm make the new project directory for you. This should only take a few moments.
Once you have a project directory set up and ready to go, it’s time to start coding the password manager application!
To start with our password manager project, we should first establish the variables, user inputs, and text prompts that will appear on the screen when we run the application.
First, let’s design a menu screen that will ask whether you would like to enter a new password, or view old ones.
menu = "" while (menu != '1' or menu != '2'): menu= input("Looking for a password or saving a new one?" "\n1. Input new password" "\n2. View saved passwords" "\n3. Exit") if (menu=='1'): #Functionality for Saving a new password if (menu == '2'): #Functionality for Viewing saved passwords. if (menu == '3'): exit()
The above code produces a text named menu that responds to 3 options. 1 will allow for you to save a new password, 2 will allow you to view saved passwords, and 3 will exit the application. With only this code, the application will not function but worry not!
Inputting new password data
The first part of functionality we need to work on is menu option 1. The first step within menu option 1 is to add the user inputs for the software name, username and password:
softwareName = input("Enter the name of the software you are using.") username = input("Enter your username for this software.") password = input("Enter your password for this software.")
After collecting all the software, username and password data, it’s time to create the encryption function. This function will be used to encrypt the data using by the Caesar Cipher.
Creating the Encryption Function
The Caesar Cipher I have created below tests the length of the given data, as well as the “shift” which is the number of letters the “char” will shift in the alphabet. If the character to be shifted is a number, it will instead shift by numbers, and if the character to be shifted is neither a letter nor a number, it will not be adjusted.
def encrypt (data, shift): encrypted = "" for i in range (len(data)): char = data[i] if (char.isupper()): encrypted += chr((ord(char) + shift - 65) % 26 + 65) elif (char.isdigit()): newNum = (int(char) + shift) % 10 encrypted += str(newNum) elif (char.islower()): encrypted += chr((ord(char) + shift - 97) % 26 + 97) else: encrypted += char return encrypted
All functions should be placed above any other main code that way there are no errors when calling the function.
Once the function is created, go into the if statement that tests: “if (menu==’1′):”, and enter the following code above or below the user inputs:
shift = 2
You can adjust the number of the shift to any number you would like. This is the number of places each character will shift down the alphabet.
Encrypting the data and saving to a file
To encrypt and subsequently save the data to a file, first create a new file with the append option, and then write the encrypted data to the file.
f = open("securePasswordFile.txt", "a") f.write(encrypt(softwareName,shift) +";|"+encrypt(username,shift) +";|"+encrypt(password,shift) +"\n") f.close()
The code above will create a file named “securePasswordFile.txt” and write all the encrypted data to the file.
Ensure each piece of data (software, username, password) is separated by a series of unique characters, so the data can be retrieved later on.
At this point, your code should look something like this:
def encrypt (password, shift): encrypted = "" for i in range (len(password)): char = password[i] if (char.isupper()): encrypted += chr((ord(char) + shift - 65) % 26 + 65) elif (char.isdigit()): newNum = (int(char) + shift) % 10 encrypted += str(newNum) elif (char.islower()): encrypted += chr((ord(char) + shift - 97) % 26 + 97) else: encrypted += char return encrypted menu = "" while (menu != '1' or menu != '2'): menu= input("Looking for a password or saving a new one?" "\n1. Input new password" "\n2. View saved passwords" "\n3. Exit") if (menu=='1'): softwareName=input("Enter the name of the software you are using.") username = input("Enter your username for this software.") password = input("Enter your password for this software.") shift = 2 f = open("securePasswordFile.txt", "a") f.write(encrypt(softwareName,shift) +";|"+encrypt(username,shift) +";|"+encrypt(password,shift) +"\n") f.close() print("Data encrypted and saved to file.") if (menu == '2'): #Functionality for Viewing saved passwords. if (menu == '3'): exit()
Decrypting and retrieving the data
Now, the only functionality left is to decrypt, and retrieve the data from the secure file. To do this, we will need to create a decrypt function in a similar fashion to our encrypt function.
Copy and paste the code from your encrypt function, replace any occurrence of “encrypt” with “decrypt” and instead of adding the shift, subtract the shift. As shown below:
def decrypt (password, shift): decrypted = "" for i in range(len(password)): char = password[i] if (char.isupper()): decrypted += chr((ord(char) - shift - 65) % 26 + 65) elif (char.isdigit()): originalNum = (int(char) - shift) % 10 decrypted += str(originalNum) elif (char.islower()): decrypted += chr((ord(char) - shift - 97) % 26 + 97) else: decrypted += char return decrypted
Place this function above or directly below the encrypt function, and then we still need to call the function.
Within the if (menu == ‘2’): if statement, open a file with the read-option, and read in each line of data by looping through the file. You can then separate each piece of data by using the unique set of characters you came up with earlier, as the delimiter. As shown below:
if (menu == '2'): print("Decrypting data in file") f = open("securePasswordFile.txt", "r") print("Software\tUsername\tPassword") for x in f: shift = 2 oneResult = x.split(";|") print(decrypt(oneResult, shift) +"\t\t"+decrypt(oneResult, shift) +"\t\t"+decrypt(oneResult, shift)) f.close()
Once you input these final pieces of code the application should be fully functional and ready to start using.
User inputs 1:
User inputs 2:
That’s all folks! Thanks for reading all the way through the article, hopefully, you have gained some rewarding knowledge that can be applied later. If you were in any way confused by reading the article, please check out the embedded youtube video which provides a clear understanding of the topics covered within this post.
This article still barely scratches the surface of what Python can do, so be sure to continue expanding your knowledge on the subject.
Just discovered Python and not sure how to start out? Check out my original article for all the know-how on how to start coding in Python.