I am facing InvalidSignature and InvalidToken error in Fernet. The encryption is proper but I am facing error in Decryption

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?

New contributor

Anushka Mahajan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật