为了账号安全,请及时绑定邮箱和手机立即绑定

如何在 Python 3 中将字节转换为字符串以连接(序列化数据,签名)

如何在 Python 3 中将字节转换为字符串以连接(序列化数据,签名)

绝地无双 2022-06-22 17:01:35
我正在使用一个原型来保护反序列化,为序列化数据添加签名,但是当我尝试将签名与序列化数据连接时会引发错误。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 pickleimport jsonimport hashlibimport hmacclass User(object):    def __init__(self, name):        self.name = namefilename = 'user.file'KEY = b'secret'user = User('david')serialized = pickle.dumps(user)#calculate the signaturesignature = 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)
查看完整描述

2 回答

?
慕妹3242003

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


查看完整回答
反对 回复 2022-06-22
?
手掌心

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)


查看完整回答
反对 回复 2022-06-22
  • 2 回答
  • 0 关注
  • 141 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号