-1

I'm trying to make an encrypted password manager. I've got almost everything done, except for saving the password along with the username and the site where I use it. When I execute the function that writes it to a file I get:

TypeError: a bytes-like object is required, not 'str'

The code is this and I'm using cryptography to encrypt the passwords:

from cryptography.fernet import Fernet
import errors


def write(text, key):
"""Encrypt and writes something to the passlist.encrypted file
Arguments:
text   -- The list that will be written in the passlist.encrypted file
key    -- The main key, generated from password"""
try:
    if type(text) == list:
        file = open('passlist.encrypted', 'wb')
        for i in text:
            message = i.encode()

            f = Fernet(key)
            encrypted = f.encrypt(message)
            print(encrypted, file = file)
            if i == text[-1]:
                file.close()
    else:
        raise errors.invalidValueTypeError

except errors.invalidValueTypeError:
    print('Error: Text must be a list')

Also, I'm trying to make that every string in the text list uses a different line and the previous text is not overwritten, but I can't make it work.

MelDur
  • 11
  • 1
  • Does this answer your question? [TypeError: a bytes-like object is required, not 'str' when writing to a file in Python3](https://stackoverflow.com/questions/33054527/typeerror-a-bytes-like-object-is-required-not-str-when-writing-to-a-file-in) – David May 16 '20 at 20:11

2 Answers2

0

you've opened the file for writing with 'wb'– from the docs:

'b' appended to the mode opens the file in binary mode: now the data is read and written in the form of bytes objects. This mode should be used for all files that don’t contain text.

if you're writing a string to a file, open that file by doing open(filename, 'w')

David
  • 424
  • 3
  • 16
0

As @David mentioned you can write the file with 'w' mode. Also, the code for writing the encrypted word in the file can be tweaked a bit to add new line

encrypted = f"{f.encrypt(message)}\n"
sam
  • 2,263
  • 22
  • 34