无法在Python中反序列化Protobuf字节字段

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

'utf-8'编解码器无法解码位置1处的0xd6字节:'utf-8'编解码器无法解码位置1处的0xd6字节,因为它是一个无效的连续字节。
字段: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;
}

你的数据是否使用 utf-8 编码? - Isma
1
这个问题帮助我解决了我的难题:https://dev59.com/nqXja4cB1Zd3GeqPXdm3 - aoh
1个回答

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

出现以下错误:"编码或错误没有字符串参数"。 - me and stuff
啊,好的,数据不是字符串而是字节数组吗? - Isma
2
仍然无法工作。错误:"'utf-8'编解码器无法解码第30-31个位置的字节:无效的续字符"。 - me and stuff
让我们在聊天中继续这个讨论 - Isma
s = str(data, 'utf-8') 给了我一个错误,提示str最多只能接受一个参数(但是给了两个)。 - CashCow
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接