无法访问类型“str”的成员“bytes”/成员“bytes”未知

问题描述 投票:0回答:1

我似乎无法将 master_pwd 字符串转换为字节。我不知道它是否已被删除,或者我是否遗漏了一些东西。

代码尚未完成,但我不想进一步,除非我找到如何将密码转换为字节。

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.bytes
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:", passw)

def add():
    name = input('Account name: ')
    pwd = input('Password: ')
    with open('passwords.txt', 'a') as f:
        f.write(name + "|" + pwd + "\n")


while True:
    mode = input("Would you like to add a new password or view existing ones (view, add), press q to quit? ").lower()
    if mode == "q":
        break

    if mode == "view":
        view()
    elif mode == "add":
        add()
    else:
        print("Invalid mode.")
        continue
python python-cryptography fernet
1个回答
0
投票

byte()
方法需要知道编码。用户输入 Python 的内容将是一个 UTF-8 字符串。代码如下:

from cryptography.fernet import Fernet
key = Fernet.generate_key()
inp = bytes( input(), 'utf-8')
print (type(inp), inp,)
print(type(key), key )

abc
的输入上输出:

abc
<class 'bytes'> b'abc'
<class 'bytes'> b'uJvfK6IJQ7DeK1Apipwnp3fju1hliXZwNp0R3ca8q84='
© www.soinside.com 2019 - 2024. All rights reserved.