In this example program, we are building a python program to safely store and retrieve the password. It stores passwords in a file. Passwords are totally secured. This program also contains a master password to use the application. Option available in the program is you can get previously-stored password. You can also add your new password. You can also check for all stored usernames. So let’s start writing Python Program to build a Simple Password Saver.
**Note: **This program is not a fully secure program to store your important passwords. This is just an idea to create one, you can make some modifications and suggestions to us via comments. 

password saver python ]

Algorithm

  • Upon Entry validity of user is checked by a master password, which is currently hardcoded as (rahulkumar).
  • If validated then we enter into an endless while loop which will show you menu to do various things. If validation failed error message will be shown and program exits.
  • we will be store all passwords as key and value pairs.

Python Program to build a Simple Password Saver App Code:

Imports and variable setups

Let’s start by importing the important imports for python. Explaining each and every line of the import section is useless and time-wasting. I will explain all the necessary ones. You can get the code from GitHub link in the last of post.

import os  
import base64  
import hashlib  
import sys  
import getpass  
import pyperclip

We are using pyperclip to copy passwords to the clipboard using python code. you can check out its description here.
We are using hashlib to create hash of any string.
Also, we are using getpass getting password from the user without exposing it.

#p = "rahulkumar"  
#hashlib.md5(p.encode()).hexdigest()  
location="D:\\\\Rahul"  
passFile="jsdfssdjcbsddaihsdhasjdakjsda.bin"  
finalPassFile=location + "/" + passFile  
# master password  
programPassword = "37dff0cd99ecc47c60aeea102185262a" #'rahulkumar'   
passDict = {}

location is location of the password file.
passFile variable is the name of password file.
programPassword variable has the master password as hex. You can generate for your name using the commented code written in the first two lines of this code.
passDict variable is dictionary used to store passwords in memory.

All of this is the setup. Let’s move towards the main code.

#all the helpers functions  
def encodeString(strToEncode):  
    # return bytes  
    return base64.encodebytes(strToEncode.encode())  
def decodeString(strToDecode):  
    # return String  
    return base64.decodebytes(strToDecode).decode()

We are using base64 is for reversible password recovery. We can also create our own hashing algorithm for maximum security. Also, we are using one function for encoding string and other for decoding string as you can see by their names.

def validateUser():  
    try:   
        p = getpass.getpass()  
    except Exception as error:   
        print('ERROR', error)   
    else:   
        if hashlib.md5(p.encode()).hexdigest() == programPassword:  
            return True  
        else:  
            print ("Wrong Password" )  
            return False

Now we are adding method validateUser to validate the user when the user tries to enter into the app for the first time. We are using try and except for the first time to getting the password and avoiding wrong input entry.

Saving and Loading

def save():  
    try:   
        file = open(finalPassFile,"wb")  
    except Exception as error:   
        print('ERROR', error)   
    else:  
        for key,value in passDict.items():  
            file.write(key)  
            file.write(value)  
        file.close()  
def load():  
    try:   
        file = open(finalPassFile,"rb")  
    except Exception as error:   
        print('ERROR', error)   
    else:   
        lines = file.readlines()  
        file.close()  
        loadingKey=True  
        keyValue = ""  
        for line in lines:  
            if loadingKey:  
                passDict\[line\] = ""  
                keyValue = line  
                loadingKey = False  
            else:  
                loadingKey = True  
                passDict\[keyValue\] = line

We are using save and load functions to save and load passDict data to the file and from the file respectively. For your understanding, we are storing the key in the first line the password in second line, second key in the third line and second password in the second line and so on.

def addPassword(key,value):  
    passDict\[encodeString(key)\] = encodeString(value)  
      
def getPassword(key):  
    #use a try and except block to safely get the password  
    return decodeString(passDict\[encodeString(key)\])  
def getAllUser():  
    load()  
    for k,v in passDict.items():  
        print(decodeString(k))

Use of these three functions is to return the value from the passDict dictionary. One for adding a password, one for getting and one for getting all the users for easiness.

def menu():  
    print("")  
    print("1. Get password")  
    print("2. Add password")  
    print("3. Show All User")  
    print("4. Exit")  
    option = 0  
    try:  
        option = int(input("Enter your choice: "))  
    except Exception as error:  
        print("Error: " + str(error))  
        menu()  
    print("")  
    if option > 4:  
        print("Error: please enter valid integer in range")  
        menu()  
    elif option == 4:  
        sys.exit(0)  
    elif option == 3:  
        getAllUser()  
    elif option == 1:  
        print("please enter website for which you need password")  
        key = input("username: ")  
        show\_on\_screen\_opt = True  
        pass\_value = ""  
        try:  
            load()  
            pass\_value = getPassword(key)  
            #print(pass\_value)  
            pyperclip.copy(pass\_value)  
            print("your password is successfully copied to clipboard, Please paste where needed")  
        except:  
            print("Password for this username is not available")  
            show\_on\_screen\_opt =False  
        if show\_on\_screen\_opt:  
            try:  
                opt = int(input("1 to show on screen: "))  
                if opt == 1:  
                    print(pass\_value)  
            except:  
                print("")  
    elif option == 2:  
        user = input("UserName/Website: ")  
        try:  
            print("Enter password")  
            user\_pass = getpass.getpass()  
            addPassword(user,user\_pass)  
            save()  
        except Exception as error:   
            print('ERROR: ', error)  
            print("do the all entry again")  
    else:  
        print("please check your inputs")  
def main():  
    print("Please validate yourself: ")  
    if validateUser():  
        while 1:  
            menu()  
    else:  
        print("Cannot verify you sorry!")

The use of menu and main functions is to show the options menu and provide the functionality to combine the whole program into one. The flow of the program is same as the post. Call main function to start executing the program.

For Easiness below is the full program. Please copy and test in your editor. You can also get it from GitHub here.

import os  
import base64  
import hashlib  
import sys  
import getpass  
import pyperclip  
  
#p = "rahulkumar"  
#hashlib.md5(p.encode()).hexdigest()  
location="D:\\\\Rahul"  
passFile="jsdfssdjcbsddaihsdhasjdakjsda.bin"  
finalPassFile=location + "/" + passFile  
# master password  
programPassword = "37dff0cd99ecc47c60aeea102185262a" #'rahulkumar'   
passDict = {}  
  
#all the helpers functions  
def encodeString(strToEncode):  
    # return is bytes  
    return base64.encodebytes(strToEncode.encode())  
def decodeString(strToDecode):  
    # return is String  
    return base64.decodebytes(strToDecode).decode()  
def validateUser():  
    try:   
        p = getpass.getpass()  
    except Exception as error:   
        print('ERROR', error)   
    else:   
        if hashlib.md5(p.encode()).hexdigest() == programPassword:  
            return True  
        else:  
            print ("Wrong Password" )  
            return False  
def save():  
    try:   
        file = open(finalPassFile,"wb")  
    except Exception as error:   
        print('ERROR', error)   
    else:  
        for key,value in passDict.items():  
            file.write(key)  
            file.write(value)  
        file.close()  
def load():  
    try:   
        file = open(finalPassFile,"rb")  
    except Exception as error:   
        print('ERROR', error)   
    else:   
        lines = file.readlines()  
        file.close()  
        loadingKey=True  
        keyValue = ""  
        for line in lines:  
            if loadingKey:  
                passDict\[line\] = ""  
                keyValue = line  
                loadingKey = False  
            else:  
                loadingKey = True  
                passDict\[keyValue\] = line  
def addPassword(key,value):  
    passDict\[encodeString(key)\] = encodeString(value)  
      
def getPassword(key):  
    #use a try and except block to safely get the password  
    return decodeString(passDict\[encodeString(key)\])  
def getAllUser():  
    load()  
    for k,v in passDict.items():  
        print(decodeString(k))  
def menu():  
    print("")  
    print("1. Get password")  
    print("2. Add password")  
    print("3. Show All User")  
    print("4. Exit")  
    option = 0  
    try:  
        option = int(input("Enter your choice: "))  
    except Exception as error:  
        print("Error: " + str(error))  
        menu()  
    print("")  
    if option > 4:  
        print("Error: please enter valid integer in range")  
        menu()  
    elif option == 4:  
        sys.exit(0)  
    elif option == 3:  
        getAllUser()  
    elif option == 1:  
        print("please enter website for which you need password")  
        key = input("username: ")  
        show\_on\_screen\_opt = True  
        pass\_value = ""  
        try:  
            load()  
            pass\_value = getPassword(key)  
            #print(pass\_value)  
            pyperclip.copy(pass\_value)  
            print("your password is successfully copied to clipboard, Please paste where needed")  
        except:  
            print("Password for this username is not available")  
            show\_on\_screen\_opt =False  
        if show\_on\_screen\_opt:  
            try:  
                opt = int(input("1 to show on screen: "))  
                if opt == 1:  
                    print(pass\_value)  
            except:  
                print("")  
    elif option == 2:  
        user = input("UserName/Website: ")  
        try:  
            print("Enter password")  
            user\_pass = getpass.getpass()  
            addPassword(user,user\_pass)  
            save()  
        except Exception as error:   
            print('ERROR: ', error)  
            print("do the all entry again")  
    else:  
        print("please check your inputs")  
def main():  
    print("Please validate yourself: ")  
    if validateUser():  
        while 1:  
            menu()  
    else:  
        print("Cannot verify you sorry!")  
  
main()

An example run of this code is attached below please check. The entered password is check, also please create Rahul folder in D drive, or change the path in the program. You can also check Bubble sort in python programming language here.