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

如何规避Python Fernet解密时出现的InvalidToken异常?

问题

原本可正常对多文件执行加密和解密操作,但当目标目录存在未加密文件时,程序会抛出InvalidToken错误,导致无法继续解密剩余加密文件。

原代码

import os
from cryptography.fernet import Fernet
import sys
import warnings

InvalidToken = False

key = b'SpecialKindKey'
fernet = Fernet(key)
encr_file_list = []

path ="C:/users/NineTail/desktop/pokemon/go/"
#we shall store all the file names in this list
filelist = []

for root, dirs, files in os.walk(path):
    for file in files:
        #append the file name to the list
        filelist.append(os.path.join(root,file))

#print all the file names
for name in filelist:
    print(name)

for file in filelist:
    with open(file, 'rb') as f:
        file_content = f.read()
        decrypted_content = fernet.decrypt(file_content)
        with open(file, 'wb') as f:
            f.write(decrypted_content)

报错信息

Traceback (most recent call last):
  File "r3.py", line 36, in <module>
    decrypted_content = fernet.decrypt(file_content)
  File "C:\Program Files\Python38\lib\site-packages\cryptography\fernet.py", line 85, in decrypt
    timestamp, data = Fernet._get_unverified_token_data(token)
  File "C:\Program Files\Python38\lib\site-packages\cryptography\fernet.py", line 121, in _get_unverified_token_data
    raise InvalidToken
cryptography.fernet.InvalidToken

解决方案

方案1:捕获异常,跳过未加密文件

原代码中自行定义InvalidToken = False会覆盖库的异常类,需先删除这行,改为从cryptography.fernet导入该异常。之后在解密逻辑中添加try-except块,捕获无效令牌异常,跳过无法解密的文件,继续处理剩余文件。

修改后的核心代码:

# 修正导入语句,删除原代码中的 InvalidToken = False
import os
from cryptography.fernet import Fernet, InvalidToken
import sys
import warnings

key = b'SpecialKindKey'
fernet = Fernet(key)
encr_file_list = []

path ="C:/users/NineTail/desktop/pokemon/go/"
filelist = []

for root, dirs, files in os.walk(path):
    for file in files:
        filelist.append(os.path.join(root,file))

for name in filelist:
    print(name)

for file in filelist:
    try:
        with open(file, 'rb') as f:
            file_content = f.read()
        decrypted_content = fernet.decrypt(file_content)
        with open(file, 'wb') as f:
            f.write(decrypted_content)
        print(f"成功解密文件: {file}")
    except InvalidToken:
        print(f"跳过未加密/无效文件: {file}")
    except Exception as e:
        print(f"处理文件 {file} 时出错: {str(e)}")

方案2:给加密文件标记后缀,精准处理

加密时为文件添加特定后缀(如.encrypted),解密时只处理带该后缀的文件,从根源避免误操作未加密文件。

配套加密代码片段

for file in filelist:
    # 跳过已加密的文件
    if file.endswith('.encrypted'):
        continue
    with open(file, 'rb') as f:
        content = f.read()
    encrypted_content = fernet.encrypt(content)
    # 生成带后缀的加密文件
    encrypted_file = file + '.encrypted'
    with open(encrypted_file, 'wb') as f:
        f.write(encrypted_content)
    # 可选:删除原文件
    # os.remove(file)

对应解密代码

filelist = []
for root, dirs, files in os.walk(path):
    for file in files:
        # 只处理带加密后缀的文件
        if file.endswith('.encrypted'):
            filelist.append(os.path.join(root, file))

for file in filelist:
    try:
        with open(file, 'rb') as f:
            file_content = f.read()
        decrypted_content = fernet.decrypt(file_content)
        # 去掉加密后缀,还原原文件名
        original_file = file[:-10]
        with open(original_file, 'wb') as f:
            f.write(decrypted_content)
        # 可选:删除加密文件
        # os.remove(file)
        print(f"成功解密文件: {file} -> {original_file}")
    except InvalidToken:
        print(f"无效加密文件: {file}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 18:11:08