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

Python使用Fernet解密文件报错:'bytes'对象无'decrypt'属性

问题解决:Fernet解密时的'bytes'/'str' object has no attribute 'decrypt'错误

你的问题核心是调用decrypt方法的对象不对:从文件读取的key只是字节串(或字符串),而decrypt是Fernet类实例的专属方法,并非字节/字符串的内置方法。

正确实现步骤:

  1. 先确保安装了cryptography库:
pip install cryptography
  1. 修正代码,通过读取的密钥创建Fernet实例,再用该实例执行解密操作:
from cryptography.fernet import Fernet

# 读取密钥文件(用with语句自动管理文件关闭)
with open('C:/Documents/key.key', 'rb') as k:
    key = k.read()

# 基于密钥创建Fernet实例
fernet = Fernet(key)

# 读取加密内容并解密
with open('C:/Documents/encrypted.txt', 'rb') as f:
    enc_content = f.read()

decrypted_content = fernet.decrypt(enc_content)
# 若需要转为字符串,可添加解码步骤
# decrypted_str = decrypted_content.decode('utf-8')

关键注意点:

  • 你读取的key必须是Fernet规范生成的有效密钥(比如通过Fernet.generate_key()生成的字节串),否则会触发无效密钥的错误。
  • 使用with语句操作文件无需手动调用close(),代码更简洁安全。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 00:45:59