代码之家  ›  专栏  ›  技术社区  ›  me and stuff

无法在python中反序列化protobuf bytes字段

  •  3
  • me and stuff  · 技术社区  · 7 年前

    我使用protobuf传递一个散列字节数组。但在尝试反序列化时,我遇到了以下错误:

    “utf-8”编解码器无法解码位置1中的字节0xd6:“utf-8”编解码器 无法解码位置1中的字节0xd6: 字段:master。哈希1

    代码很简单:

    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;
    }
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Isma    7 年前

    您使用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)