Python3.7中加密.pkl文件的内存解密及Unpickling问题咨询
问题修复方案
错误原因
- 第一处错误:
file.read(file)写法不符合规范,read()方法无参数时默认读取文件全部内容,不需要传入文件对象作为参数。 - 第二处错误:
pickle.load()要求传入具备读能力的类文件对象,你传入的decrypted_data是解密后的字节串,不满足参数要求,触发对应的TypeError。
修复代码
最简单的方案是直接使用pickle.loads()方法,该方法原生支持直接接收字节串完成反序列化:
import pickle as p from cryptography.fernet import Fernet f = Fernet(key) with open(filepath, "rb") as file: encrypted_data = file.read() decrypted_data = f.decrypt(encrypted_data) # 用loads()替代load()直接读取字节串 vectorizer = p.loads(decrypted_data)
如果你希望继续使用pickle.load(),也可以用io.BytesIO把字节串包装为类文件对象:
import pickle as p from cryptography.fernet import Fernet import io f = Fernet(key) with open(filepath, "rb") as file: encrypted_data = file.read() decrypted_data = f.decrypt(encrypted_data) vectorizer = p.load(io.BytesIO(decrypted_data))
两种实现效果完全一致,前者代码更简洁,无需额外导入依赖。
内容的提问来源于stack exchange,提问作者Dario Shehni
相关产品推荐
相关产品推荐

