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

unable to deserialize protobuf bytes field in python

我正在使用 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)

我认为这是 encoding\decoding 的简单问题,但我不知道该怎么做。

这是在 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)

编辑

如果仍然无法正常工作,请尝试 return 来自您的 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)