【问题标题】:unable to deserialize protobuf bytes field in python无法反序列化python中的protobuf字节字段
【发布时间】:2017-11-01 08:19:01
【问题描述】:

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

【问题讨论】:

标签: python protocol-buffers decode encode


【解决方案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)

【讨论】:

  • 收到此错误:“没有字符串参数的编码或错误”
  • 啊好吧,难道数据已经不是字符串而是字节数组了吗?
  • 还是不行。错误:“'utf-8' 编解码器无法解码位置 30-31 中的字节:无效的继续字节”
  • 我用另一种方法再次更新了答案。如果仍然无法正常工作,则错误不在您的 python 或 c# 代码上。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多