【问题标题】:How to convert bytes to string in Python 3 to concatenate(serialized_data,signature)如何在 Python 3 中将字节转换为字符串以进行连接(序列化数据,签名)
【发布时间】: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


【解决方案1】:

使用.digest() 而不是.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

【讨论】:

    【解决方案2】:

    试试这个

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-16
      • 2012-01-16
      • 1970-01-01
      • 2018-06-11
      • 2019-01-25
      • 1970-01-01
      • 2016-02-01
      • 1970-01-01
      相关资源
      最近更新 更多