2 回答

TA贡献1824条经验 获得超6个赞
使用.digest()not.hexdigest()获取可以附加到序列化数据字节字符串的字节字符串。打开文件进行二进制读/写:
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).digest() # not .hexdigest()
with open(filename, 'wb') as file_object: # binary write
file_object.write(signature + serialized)
with open(filename, 'rb') as file_object: # binary read
raw_data = file_object.read()
if len(raw_data) >= len(signature): # need >= here
read_signature = raw_data[:len(signature)]
read_data = raw_data[len(signature):]
computed_signature = hmac.new(KEY, read_data, hashlib.sha256).digest() # not .hexdigest()
if hmac.compare_digest(computed_signature, read_signature):
userDeserialized = pickle.loads(read_data)
print (userDeserialized.name)
输出:
david

TA贡献1942条经验 获得超3个赞
尝试这个
with open(filename, 'wb') as file_object:
#Adding the signature to the data
print(type(serialized))
print(type(signature))
#serializedStr = serialized.decode('utf-8')
s = bytearray(signature)
s.extend(bytes(serialized, 'utf-8'))
file_object.write(s)
添加回答
举报