Here is the complete code:
`import csv
from cryptography.fernet import Fernet
# Generate a key for encryption and decryption
key = Fernet.generate_key()
cipher_suite = Fernet(key)
class InvalidChoice(Exception):
pass
def pass_manage():
try:
choice = int(input("Enter your choice: "))
if choice not in [1, 2, 3, 4]:
raise InvalidChoice("This choice is not valid.")
except ValueError:
print("You should enter a number.")
pass_manage()
return
except Exception as error:
print(error)
pass_manage()
return
def get_pass(name):
with open('accounts.csv', mode='r') as csv_file:
csv_reader = csv.DictReader(csv_file)
for row in csv_reader:
if row["acc_name"] == name:
decoded_pass = cipher_suite.decrypt(row["password"]).decode()
print(f'{row["acc_name"]}: {decoded_pass}')
def view():
with open('accounts.csv', mode='r') as csv_file:
csv_reader = csv.DictReader(csv_file)
for row in csv_reader:
decoded_pass = cipher_suite.decrypt(row["password"]).decode()
print(f'{row["acc_name"]}: {decoded_pass}')
def add_details(name, set_pass):
field_names = ['acc_name', 'password']
encoded_pass = cipher_suite.encrypt(set_pass.encode()).decode()
entry = {'acc_name': name, 'password': encoded_pass}
with open('accounts.csv', 'a', newline='') as csv_file:
dictwriter_object = csv.DictWriter(csv_file, fieldnames=field_names)
dictwriter_object.writerow(entry)
def update(name, new_pass):
with open('accounts.csv', mode='r') as csv_file:
csv_reader = csv.DictReader(csv_file)
rows = list(csv_reader)
updated = False
for row in rows:
if row["acc_name"] == name:
row["password"] = cipher_suite.encrypt(new_pass.encode()).decode()
updated = True
break
if not updated:
print(f"No account found with the name: {name}")
return
field_names = rows[0].keys()
with open('accounts.csv', mode='w', newline='') as csv_file:
csv_writer = csv.DictWriter(csv_file, fieldnames=field_names)
csv_writer.writeheader()
csv_writer.writerows(rows)
if choice == 1:
name = input("Enter account name: ")
get_pass(name)
elif choice == 2:
view()
elif choice == 3:
name = input("Enter account name: ")
set_pass = input("Enter password: ")
add_details(name, set_pass)
elif choice == 4:
name = input("Enter account name: ")
new_pass = input("Enter new password: ")
update(name, new_pass)
else:
print("Invalid choice. Please enter a number between 1 and 4.")
pass_manage()
print("nWelcome to password manager:")
print("How can we help you today?")
print("1. Need password for an account?")
print("2. Need to view passwords for all accounts?")
print("3. Need to add new account and password?")
print("4. Update password")
pass_manage()`
I wanted to print decrypted passwords when option 1 or 2 were selected. Instead, I was facing
File ~anaconda3libsite-packagescryptographyfernet.py:133 in _verify_signature
h.verify(data[-32:])
File ~anaconda3libsite-packagescryptographyhazmatprimitiveshmac.py:70 in verify
ctx.verify(signature)
File ~anaconda3libsite-packagescryptographyhazmatbackendsopensslhmac.py:84 in verify
raise InvalidSignature(“Signature did not match digest.”)
InvalidSignature: Signature did not match digest.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File ~anaconda3libsite-packagesspyder_kernelspy3compat.py:356 in compat_exec
exec(code, globals, locals)
File untitled3.py:97
pass_manage()
File untitled3.py:76 in pass_manage
get_pass(name)
File untitled3.py:32 in get_pass
decoded_pass = cipher_suite.decrypt(row[“password”]).decode()
File ~anaconda3libsite-packagescryptographyfernet.py:90 in decrypt
return self._decrypt_data(data, timestamp, time_info)
File ~anaconda3libsite-packagescryptographyfernet.py:151 in _decrypt_data
self._verify_signature(data)
File ~anaconda3libsite-packagescryptographyfernet.py:135 in _verify_signature
raise InvalidToken
InvalidToken
How can I solve this? This is my first time using this module. apart from this file, I have maintained accounts.csv file. Any idea what to do?
Anushka Mahajan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.