0
votes

I am trying to encrypt a password, store that password in a text file and then later I would retrieve that encrypted password and decrypt it in python. I've gotten the encryption working, and storing it in the text file however when trying to decrypt it again it says:

AttributeError: 'str' object has no attribute 'decode'. I copy and pasted the encrypted message which was in bytes I think into the text file, so Im not sure how else to decrypt it.

salt = b'salt123'
kdf = PBKDF2HMAC(
    algorithm=hashes.SHA256(),
    length=32,
    salt=salt,
    iterations=100000,
    backend=default_backend()
)

test_password = 'test123'.encode()
key = base64.urlsafe_b64encode(kdf.derive(test_password))
f = Fernet(key)
encrypted = f.encrypt(test_password) #This is the encrypted password which I copy and pasted into the text file

password = []
f = open("Passwords.txt", "r")
if f.mode == 'r':
    for line in f:
        password.append(line)
f.close()

#password[2] is the encrypted password 
decrypted_pass = f.decrypt(password[2]) #Error AttributeError: 'str' object has no attribute 'decode'

EDIT: made a mistake, meant to decrypt in the last line not decode

1
Just so you know, encoding is not the same as encrypting - Nathan
Please share the entire error message, as well as a minimal reproducible example. I would recommend reading the following article: ericlippert.com/2014/03/05/how-to-debug-small-programs - AMC

1 Answers

1
votes

Your code makes no sense. You can of course encrypt your password using a key derived from your password. However, to decrypt it you need the original password again. If you have this password then you don't need to decrypt it again. You desperately need to read up on PBKDF2 and how it can be used for password hashing.

Then you store the encrypted password, and you try and decode it as if it was an encoded byte string, i.e. bytes or bytearray. That makes no sense, character-encoding is converting from string to bytes, and character-decoding is conversion from bytes to string (using a specific character set). Read up on character encoding as well.

The source of the error is probably that you are replacing the Fernet instance with a file in variable f. Use differently named variables for those.