gpt4 book ai didi

python - 无法反序列化python中的protobuf字节字段

转载 作者:行者123 更新时间:2023-12-05 06:37:49 24 4
gpt4 key购买 nike

我正在使用 protobuf 传递一个哈希字节数组。但是在尝试反序列化时,出现以下错误:

'utf-8' codec can't decode byte 0xd6 in position 1: 'utf-8' codec can't decode byte 0xd6 in position 1: invalid continuation byte in field: master.hash1

代码很简单:

a = message.ParseFromString(data)

我相信这是一个简单的编码\解码问题,但我不知道该怎么做。

这是在 C# 中对数据进行编码的代码:

public byte[] HmacSign(string key, string message)
{
var encoding = new System.Text.ASCIIEncoding();
byte[] keyByte = encoding.GetBytes(key);

HMACSHA1 hmacsha1 = new HMACSHA1(keyByte);

byte[] messageBytes = encoding.GetBytes(message);
byte[] hashmessage = hmacsha1.ComputeHash(messageBytes);

return hashmessage;
}

最佳答案

您正在使用 ASCII 对数据进行编码,因此您还必须使用 ASCII 进行解码:

s = str(data, 'ascii')
message.ParseFromString(s)

如果您更喜欢使用 UTF-8,请更改您的 C# 代码的编码:

public byte[] HmacSign(string key, string message)
{
var encoding = new System.Text.UTF8Encoding();
byte[] keyByte = encoding.GetBytes(key);

HMACSHA1 hmacsha1 = new HMACSHA1(keyByte);

byte[] messageBytes = encoding.GetBytes(message);

byte[] hashmessage = hmacsha1.ComputeHash(messageBytes);
return hashmessage;
}

然后在你的 python 代码中使用 UTF-8:

s = str(data, 'utf-8')
message.ParseFromString(s)

编辑

如果仍然无法正常工作,请尝试从您的 C# 代码返回一个字符串:

public string HmacSign(string key, string message)
{
var encoding = new System.Text.UTF8Encoding();
byte[] keyByte = encoding.GetBytes(key);
byte[] messageBytes = encoding.GetBytes(message);
using (var hmacsha new HMACSHA1(keyByte))
{
byte[] hashmessage = hmacsha.ComputeHash(messageBytes);
return Convert.ToBase64String(hashmessage);
}
}

在你的 Python 代码中:

import base64
s = base64.b64decode(data).decode('utf-8')
message.ParseFromString(s)

关于python - 无法反序列化python中的protobuf字节字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47050746/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com