2017-11-01 1 views
0

ハッシュされたバイト配列をprotobufを使って渡しています。しかし、それをデシリアライズしようとしている間、私は次のエラーを取得しています: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) 

私はそれがエンコーディング\復号の単純な問題であると考えているが、私はありません持っていますどのようにそうするのかアイデア。

これは、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; 
} 
+0

ですあなたのデータはutf-8でエンコードされていますか? – Isma

答えて

0

あなたはデコードにも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) 

EDIT

それでも動作しない場合は、お使いの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) 
+0

このエラーが発生しました:「文字列引数を持たないエンコーディングまたはエラー」 –

+0

ああ、データは文字列ではなくbytearrayであることができますか? – Isma

+0

はい。これはバイト配列です。 –

関連する問題