You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Fernet解密字符串时遇InvalidToken及TypeError问题求助

密码管理器解密时触发InvalidToken错误

我正在开发一个基于Fernet库的密码管理项目,已经完成密码输入、加密和存储功能,但在检索并解密密码时,持续抛出cryptography.fernet.InvalidToken错误,完整报错栈如下:

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

用于检索和解密的代码如下:

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()

我尝试将文件打开模式从'r'改为'rb',结果又触发新错误:

TypeError: a bytes-like object is required, not 'str' at user, passw = data.split(":")

当前环境细节:

  • self.key为b'<key>'字节格式,key.key文件中仅存储去掉b''包裹的纯密钥字符串
  • 密码文件中已加密的密码格式示例:
Site:b'gAAAAABl9KjKHh4MaltYyguafWmjwNjd35wbvfyMZMZEu-t3pabud_B7TDRIjVBaAWKkeZURYN0IGDsKD2XKkdtN2yycFrBlrw=='

内容的提问来源于stack exchange,提问作者Neo Anderson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 20:13:15