I’m kind of a beginner still and I’m making a simple password manager in python using the cryptography module. The user can enter a program name and a password, and it is encrypted and then written to a file. They can also view passwords added to the file. When the user selects this, they enter the name of the program/service they are trying to find, and it returns the matching password by decrypting the file line by line and checking if the program name is in that file. I hope this makes sense.
The issue I’m having is I get raise InvalidToken cryptography.fernet.InvalidToken
when the program attempts to decrypt lines from the file after selecting “view” and entering a name, even when the file is not empty. I’m really unsure why, as the key is not generated in the program, it is stored in a file so the same key is read each time the program runs. I am already reading the file in bytes, not strings. I also have another simpler program which uses the same file and can successfully encrypt and decrypt from a file so I have a feeling I’ve made a mistake somewhere else.
Here is my program (error occurs at line 58):
from cryptography.fernet import Fernet
#Get key from file
filekey = open("filekey.key", "rb")
key = filekey.read()
fernet = Fernet(key)
filekey.close()
cmd = "" #Force entry to loop
#Run until user quits
while cmd != "quit":
cmd = input("[add | view | quit] ")
#Input validation loop
while cmd not in ["add", "view", "quit"]:
print("Not a valid command. Try again.")
cmd = input("[add | view | quit]")
#Run if user enters "add"
if cmd == "add":
#Get user input for name and password
name = input("Enter name: ")
pwd = input("Enter password: ")
#Concatenate and encode input
new_line = name + " " + pwd
byte_new_line = new_line.encode()
#Encrypt and convert to string
enc_line = fernet.encrypt(byte_new_line)
enc_line_str = str(enc_line)
#Write string to file
outfile = open("passwords.data", "a")
outfile.write(enc_line_str)
outfile.close()
#Run if user enters "view"
if cmd == "view":
found = False #Keep track of whether name is present in file
#Get user input for name to find
search = input("Name to search for: ")
#Open file to search from
infile = open("passwords.data", "rb")
line = infile.readline()
#Read each line of file
while line != "":
line = infile.readline()
#Decrypt line and convert to string
line_dec = fernet.decrypt(line) #Error here
line_dec_str = str(line_dec)
#Get index of name in decoded string
index = line_dec_str.find(name)
#Run if name is found in string
if index != -1:
#Change found to True and print string
found = True
print(line_dec_str)
#Display error if name not found
if found == False:
print("Error: name not found in file. Try again.")
infile.close()
Any help would be greatly appreciated ☺️