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

我正在使用一个原型来保护反序列化,为序列化数据添加签名,但是当我尝试将签名与序列化数据连接时会引发错误。


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)


绝地无双
浏览 142回答 2
2回答

慕妹3242003

使用.digest()not.hexdigest()获取可以附加到序列化数据字节字符串的字节字符串。打开文件进行二进制读/写: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).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

手掌心

尝试这个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)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python