pythonpython-cryptographyfernet

Cannot access member 'bytes' for type 'str' / Member 'bytes' is unknown


I can not seem to transform the master_pwd string into bytes. I do not know if it's been removed or am I missing something.

The code is not done yet but I do not want to go further unless I find out how to transform the pwd into bytes.

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

Solution

  • The byte() method needs to know the encoding. What comes from user input to Python will be an UTF-8 string. The following code:

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

    outputs on input of abc:

    abc
    <class 'bytes'> b'abc'
    <class 'bytes'> b'uJvfK6IJQ7DeK1Apipwnp3fju1hliXZwNp0R3ca8q84='
    

    Knowing this above and applying to your code gives:

    master_pwd = bytes ( input("What is the master password? "), 'utf-8')
    key = load_key() + master_pwd