I am trying a project that involves encrypting passwords using Fernet library. I have been able to enter, encrypt, and store passwords, but I keep getting the following error when I try to retrieve and decrypt the password.
Traceback (most recent call last):
File "D:\Documents\python\practiceProjects\05 passwordManager\passwordManageV2.py", line 104, in modules
pm.view()
File "D:\Documents\python\practiceProjects\05 passwordManager\passwordManageV2.py", line 82, in view
print (f'\nUser: {user}, Password: {***Fernet(self.key).decrypt(passw)***.decode()}\n')
File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\site-packages\cryptography\fernet.py", line 84, in decrypt
timestamp, data = ***Fernet._get_unverified_token_data(token)***
File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\site-packages\cryptography\fernet.py", line 118, in _get_unverified_token_data
raise InvalidToken
cryptography.fernet.InvalidToken<br/>
The code used to retrieve and decrypt the password is:
from cryptography.fernet import Fernet
import glob
import os
class PasswordManager:
def __init__(self):
self.key = None
self.password_file = None
def load_key (self):
with open('key.key', 'rb') as f:
self.key = f.read()
def num_file_check (self):
file = glob.glob('*.txt')
self.password_file = file[0]
if self.key == None:
self.load_key ()
def view (self):
self.num_file_check ()
with open(self.password_file, 'r') as f:
for line in f.readlines():
data = line
try:
user, passw = data.split(":")
print (f'\nUser: {user}, Password: {Fernet(self.key).decrypt(passw).decode()}\n')
except ValueError:
continue
pm = PasswordManager ()
pm.view()
I tried adding 'rb' to with open(self.password_file, 'r') as f:, as suggested. However, I received:
TypeError: a bytes-like object is required, not 'str' at user, passw = data.split(":").*
The self.key is in the form b'key' while the only the key (minus the b' ') is stored in the key.key file. Further, when I view the password file, I can see the password was encrypted before being written to the file
Site:b'gAAAAABl9KjKHh4MaltYyguafWmjwNjd35wbvfyMZMZEu-t3pabud_B7TDRIjVBaAWKkeZURYN0IGDsKD2XKkdtN2yycFrBlrw=='
The input files weren't provided, but if the password file has a
Siteentry like shown, the input file was written incorrectly and should not have theb''around it which is thestr()representation of abytesobject.Below generates a fresh
key.keyandpasswords.txtfile containing the encryption key and a couple of username/password lines, respectively. The OP's code is modified to read from these files correctly:Outputs:
key.key (ASCII-only):
passwords.txt (UTF-8-encoded):
Terminal (subject to font support):