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

cryptography.fernet解密抛InvalidToken但仍正常解密问题

问题根因

代码存在逻辑错误,和加密文本差异无关。
异常触发原因是解密脚本的文件过滤逻辑写错了:遍历目录时,本来要跳过encryptor.py、decryptor.py、thekey.key三个不需要解密的文件,但过滤分支里只写了pass占位,没有跳过后续逻辑,导致存储密钥的thekey.key文件本身也被加入了待解密文件列表。
Fernet尝试解密根本不是加密生成的密钥文件时,自然会抛出InvalidToken异常。这也是为什么所有加密文件都能正常解密——这些文件处理完之后,程序才轮到处理thekey.key,最后一步抛错。

错误代码片段

解密脚本中出错的文件遍历逻辑如下:

for file in os.listdir():
    if file == "encryptor.py" or file == "decryptor.py" or file =="thekey.key":
        pass # 仅占位,不会跳过后续的文件加入列表操作
    if os.path.isfile(file):
        files.append(file)
修复方法

将过滤分支里的pass替换为continue即可,和加密脚本的过滤逻辑保持一致:命中排除规则时直接跳过本轮循环,不把排除文件加入待处理列表。
修复后的完整解密脚本代码:

import os
from cryptography.fernet import Fernet
files = []
key=None

for file in os.listdir():
    if file == "encryptor.py" or file == "decryptor.py" or file =="thekey.key":
        continue
    if os.path.isfile(file):
        files.append(file)

with open("thekey.key","rb") as keyacceptor:
    key=keyacceptor.read()


for file in files:
    with open(file,"rb") as openedfile:
        content1=openedfile.read()
        decrypted_content = Fernet(key).decrypt(content1)
    with open(file,"wb") as arch:
        arch.write(decrypted_content)
注意事项
  • 遍历文件做过滤时,pass只是空语句占位,不会终止当前轮次的后续代码执行,要跳过本轮剩余逻辑必须使用continue。
  • 修复后运行脚本不会再抛出InvalidToken异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 17:57:25