我正在使用一个原型来保护反序列化,为序列化数据添加签名,但是当我尝试将签名与序列化数据连接时会引发错误。
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' codec can't decode byte 0x80 in position 0: invalid start byte
如何将签名添加到序列化数据中?
完整代码
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)
慕妹3242003
手掌心
相关分类