Reputation: 33
I'm working on a password manager app and i want to hash passwords with Fernet, the idea is that I'm writing a password into a file hashed then retrieve it when the user asks here is my code
note : the code works properly if there is one password in the file called secrets.txt -the main problem is that the code not running with multi lines in secrets.txt
key = Fernet.generate_key()
password = '123456789'
write_record("facebook","ali",password,key)
read_record(key)
def write_record(site,account,password,key):
f = Fernet(key)
token = f.encrypt(bytes(password,'utf-8'))
with open ('secrets.txt','a') as file:
file.write(f"{site},{account},{str(token)}\n")
def read_record(key):
f = Fernet(key)
with open ('secrets.txt','r') as file:
lines = file.readlines()
for line in lines:
line = line.strip().replace('\n', '')
print("line is "+line)
token = line.split(",")[2]
print(token)
token = token[2:-1]
token = token.encode()
print(token)
print(f.decrypt(token))
and here is the error I'm getting
line is facebook,ali,b'gAAAAABkLyRCekwyD5p5MMmaNxee6quDhlv9zx5e6Qghfv6jjubsGtP5m5F8YaB1LEPBq90-ab1VxK5oqOHmNStNbulSBMCtXQ=='
b'gAAAAABkLyRCekwyD5p5MMmaNxee6quDhlv9zx5e6Qghfv6jjubsGtP5m5F8YaB1LEPBq90-ab1VxK5oqOHmNStNbulSBMCtXQ=='
b'gAAAAABkLyRCekwyD5p5MMmaNxee6quDhlv9zx5e6Qghfv6jjubsGtP5m5F8YaB1LEPBq90-ab1VxK5oqOHmNStNbulSBMCtXQ=='
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/cryptography/fernet.py", line 119, in _verify_signature
h.verify(data[-32:])
File "/usr/lib/python3/dist-packages/cryptography/hazmat/primitives/hmac.py", line 74, in verify
ctx.verify(signature)
File "/usr/lib/python3/dist-packages/cryptography/hazmat/backends/openssl/hmac.py", line 75, in verify
raise InvalidSignature("Signature did not match digest.")
cryptography.exceptions.InvalidSignature: Signature did not match digest.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/mido/Desktop/project.py", line 44, in <module>
main()
File "/home/mido/Desktop/project.py", line 8, in main
read_record(key)
File "/home/mido/Desktop/project.py", line 32, in read_record
print(f.decrypt(token))
File "/usr/lib/python3/dist-packages/cryptography/fernet.py", line 80, in decrypt
return self._decrypt_data(data, timestamp, time_info)
File "/usr/lib/python3/dist-packages/cryptography/fernet.py", line 137, in _decrypt_data
self._verify_signature(data)
File "/usr/lib/python3/dist-packages/cryptography/fernet.py", line 121, in _verify_signature
raise InvalidToken
cryptography.fernet.InvalidToken
and here is the file content:
facebook,ali,b'gAAAAABkLyRCekwyD5p5MMmaNxee6quDhlv9zx5e6Qghfv6jjubsGtP5m5F8YaB1LEPBq90-ab1VxK5oqOHmNStNbulSBMCtXQ=='
facebook,ali,b'gAAAAABkLySj1RzbJMCFYrDJw8a2dNyfYMlwyiq1be818DwzU7RCWnEiUFGDS2I5DHNt7jmFf2mEm_q40h95HGfeSExTNumd-A=='
Upvotes: 2
Views: 482