【发布时间】:2019-10-11 22:19:59
【问题描述】:
我正在使用一个原型来保护反序列化,为序列化数据添加签名,但是当我尝试将签名与序列化数据连接时会引发错误。
with open(filename, 'w') as file_object:
#Adding the signature to the data
file_object.write(signature + serialized)
TypeError: 只能将 str(不是“字节”)连接到 str
如果我尝试将序列化数据转换为字符串,它也会引发错误
with open(filename, 'w') as file_object:
#Adding the signature to the data
serializedStr = serialized.decode('utf-8')
file_object.write(signature + serializedStr)
serializedStr = serialized.decode('utf-8') UnicodeDecodeError: 'utf-8' 编解码器无法解码位置 0 的字节 0x80:无效的起始字节
如何将签名添加到序列化数据中?
完整代码
import pickle
import json
import hashlib
import hmac
class User(object):
def __init__(self, name):
self.name = name
filename = 'user.file'
KEY = b'secret'
user = User('david')
serialized = pickle.dumps(user)
#calculate the signature
signature = hmac.new(KEY, serialized, hashlib.sha256).hexdigest()
with open(filename, 'w') as file_object:
#Adding the signature to the data
print(type(serialized))
print(type(signature))
#serializedStr = serialized.decode('utf-8')
file_object.write(signature + serialized)
with open(filename, 'rb') as file_object:
raw_data = file_object.read()
if(len(raw_data) == len(signature)):
read_signature = raw_data[:len(signature)]
read_data = raw_data[len(signature):]
computed_signature = hmac.new(KEY, read_data, hashlib.sha256).hexdigest()
if hmac.compare_digest(computed_signature, read_signature):
userDeserialized = pickle.loads(read_data)
print (userDeserialized.name)
【问题讨论】:
-
恐怕,将其解码为 utf-8 将不起作用,因为 pickle 转储的数据具有另一种编码,但如果您需要将其转换为 str,您可以使用
latin1 -
@Take_Care_ 尊敬的先生,编码为
latin1对我来说就像一个魅力。
标签: python python-3.x