import csv import random import string import os import sqlite3 from Crypto.Cipher import AES # path "C:\Users\eps.scl\Desktop\temp.txt" # ANSI color black = "\033[0;30m" red = "\033[0;31m" green = "\033[0;32m" yellow = "\033[0;33m" white = "\033[0;37m" cyan = "\033[0;36m" nocolor = "\033[0m" conn = sqlite3.connect('pwd.db') cursor=conn.cursor() cursor.execute(''' create table if not exists manager( pwd VARCHAR(15) PRIMARY KEY ) ''') result = cursor.execute('select * from manager') file=result.fetchall() if file == []: password=input('Enter your new password') print('password created') ins=f'insert into manager(pwd) values(?)' cursor.execute(ins, (password,)) conn.commit() else: password = input('Enter your password') print(file) if password == file[0][0]: print('Successfully logged in') else: print('wrong password entered') key=password conn.close() def genPasswd(password: str): """ Password must be 16, 24 or 32 bytes long. Function checks length of password and returns string of matching length. """ length = len(password) if length not in (16, 24, 32): if length > 24: password += " " * (32 - length) elif length > 16: password += " " * (24 - length) elif length < 16: password += " " * (16 - length) return password.encode() def encrypt(title: str, key: str, password: str): """ title: Identifying name of the data stored key: the master password password: the password to be stored """ cipher = genPasswd(key) line = AES.new(cipher, AES.MODE_EAX) ciphertext, tag = line.encrypt_and_digest(password.encode()) with open(r"temp.txt", "a", newline="") as store: writer = csv.writer(store, delimiter=",") writer.writerow([title, ciphertext, tag, line.nonce]) def decrypt(key): """ Decrypts all data. """ cipher = genPasswd(key) with open(r"temp.txt", "r", newline="") as store: reader = list(csv.reader(store, delimiter=",")) data = [] try: for line in reader: lock = AES.new(cipher, AES.MODE_EAX, eval(line[3])) data.append((line[0], lock.decrypt_and_verify(eval(line[1]), eval(line[2])).decode())) except ValueError: print(red+"Invalid password"+nocolor) if data: print(yellow+"{:<10} {:<10}\n".format("Title", "Password")+nocolor) for line in data: print(yellow+"{:<10} {:<10}".format(line[0], line[1])+nocolor) def hashtitle(title): cipher = genPasswd(key) with open(r"temp.txt", "r", newline="") as store: reader = list(csv.reader(store, delimiter=",")) try: data = {} for line in reader: lock = AES.new(cipher, AES.MODE_EAX, eval(line[3])) data[line[0]] = line[1], line[2], line[3] try: datareq = data[title] except KeyError: print(red+"Unable to find entry"+nocolor) return else: return datareq except ValueError: print(red+"Invalid password"+nocolor) def moditem(title): record = createBufferList(title) if record == None: return field = input("Enter field to be changed"+cyan+"(title, password)"+nocolor+": ") fieldIndex = {"title": 1, "username": 2, "password": 3}.get(field.lower()) if fieldIndex == None: print(red+"Unknown Field"+nocolor) return newField = input(f"Enter new {field}: ") if not newField: print(red+"Invalid Data."+nocolor) return if fieldIndex == 1: hashbin = hashtitle(title) deleteitem(title) with open(r"temp.txt", "a", newline="") as store: writer = csv.writer(store, delimiter=",") writer.writerow([newField, *hashbin]) print(green+"Successfully modified data."+nocolor) elif fieldIndex == 2: pass elif fieldIndex == 3: deleteitem(title) encrypt(title, key, newField) print(green+"Successfully modified data."+nocolor) def listOftitles(): with open(r"temp.txt", "r", newline="") as store: reader = list(csv.reader(store, delimiter=",")) data = [] for line in reader: data.append(line[0].lower().strip()) return data def createBufferList(title): with open(r"temp.txt", "r", newline="") as store: reader = list(csv.reader(store, delimiter=",")) record = [] for line in reader: if line[0] == title: continue record.append(line) if record == reader: print(red+"Item not found"+nocolor) return return record def deleteitem(title): record = createBufferList(title) if record == None: return with open(r"temp.txt", "w", newline="") as store: writer = csv.writer(store, delimiter=",") writer.writerows(record) def generatePassword(): """ Generates a random password and asks to save the password. """ count = input("Enter length of password (Default - 12): ") try: count = int(count) except ValueError: print("Using default value - 12\n") count = 12 password = "".join( random.choice(string.ascii_letters + string.digits) for _ in range(int(count)) ) print("-" * os.get_terminal_size()[0]) print(yellow+f"{password}"+nocolor) print("-" * os.get_terminal_size()[0]) save = input("Save Password? y/n: ") if save == "y": title = input("Enter a title: ") if title in listOftitles(): print(red+"This item already exists"+nocolor) return elif not title: print(red+"Invalid input: cannnot accept empty name."+nocolor) return encrypt(title, key, password) print(green+"Successfully created data."+nocolor) elif save == "n": pass else: pass def main(): while True: print("\n"+"-" * os.get_terminal_size()[0]) ## sys.stdout.write("\033[FF") # Cursor up one line print(cyan+"1:"+nocolor+" View all Passwords") print(cyan+"2:"+nocolor+" Create a new Password Entry") print(cyan+"3:"+nocolor+" Modify Existing Password Entry") print(cyan+"4:"+nocolor+" Delete a Password Entry") print(cyan+"5:"+nocolor+" Generate a New Random Password") print(cyan+"q:"+nocolor+" Quit") choice = input("Enter your choice"+cyan+"(1, 2, 3, 4, 5, q)"+nocolor+": ") print("-" * os.get_terminal_size()[0]) os.system('cls') if choice == "1": decrypt(key) elif choice == "2": title = input("Enter a title: ") if title in listOftitles(): print(red+"Invalid name; this name is already in use."+nocolor) continue elif not title: print(red+"Cannot accept an empty value."+nocolor) continue pw = input("Enter a Password: ") if not pw: print(red+"Cannot accept an empty value."+nocolor) continue encrypt(title, key, pw) print(green+"Successfully created password."+nocolor) elif choice == "3": while True: title = input( "Enter the title of the password to be modified(press Enter to list): " ) if title == "": decrypt(key) else: break moditem(title) elif choice == "4": while True: title = input( "Enter the title of the password to be deleted(press Enter to list): " ) if title == "": decrypt(key) else: break deleteitem(title) elif choice == "5": generatePassword() elif choice == "q": break if __name__ == "__main__": try: main() except KeyboardInterrupt: pass