0

我是 python 新手,我正在做这些小项目,以便我可以构建自己。这是一个小项目,它只会使用主密码添加和查看用户名和密码。我能够通过加密文件中的密码添加用户名和密码。但是要查看密码,它在 23 和 39 行显示了两个问题。而且主密码也不起作用。

from cryptography.fernet import Fernet

'''
def write_key():
    key = Fernet.generate_key()
    with open("key.key", "wb") as key_file:
        key_file.write(key)'''

def load_key():
    file = open("key.key", "rb")
    key = file.read()
    file.close()
    return key

master_pwd = input("What is the master password? ")
key = load_key() + master_pwd.encode()
fer = Fernet(key)

def view():
    with open('passwords.txt', 'r') as f:
        for line in f.readlines():
            data = line.rstrip()
            user, passw = data.split("|")
            print("User:", user, "| Password:",
                  fer.decrypt(passw.encode()).decode())

def add():
    name = input("Account name: ")
    pwd = input("Input password: ")

    with open('passwords.txt', 'a') as f:
        f.write(name + "|" + fer.encrypt(pwd.encode()).decode() + "\n")

while True:
    mode = input("Would you like to add a new password or view existing  ones?(Add/View):\nOtherwise press 'Q' to Quit: \n").lower()
    if mode == "q":
        break
    elif mode == "view":
        view()
    elif mode == "add":
        add()
    else:
        print("Invalid mode.")
        continue

问题如图所示。

4

0 回答 0