Python使用Fernet解密文件报错:'bytes'对象无'decrypt'属性
问题解决:Fernet解密时的'bytes'/'str' object has no attribute 'decrypt'错误
你的问题核心是调用decrypt方法的对象不对:从文件读取的key只是字节串(或字符串),而decrypt是Fernet类实例的专属方法,并非字节/字符串的内置方法。
正确实现步骤:
- 先确保安装了
cryptography库:
pip install cryptography
- 修正代码,通过读取的密钥创建
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
相关产品推荐
相关产品推荐

