2017-11-01 1 views
0

해시 바이트 배열 protobuf를 사용하여 전달 중입니다. 직렬화하는 동안, 나는 다음과 같은 오류 받고 있어요 : 나는 그것을 인코딩 \ 디코딩하는 간단한 문제라고 생각파이썬에서 protobuf 바이트 필드를 비 직렬화 할 수 없습니다

a = message.ParseFromString(data) 

,하지만 난 더 있습니다

'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

를 코드는 단순히 없습니다 그렇게하는 방법.

는 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) 

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; 
} 

을 다음 파이썬 코드에서 UTF-8을 사용 : UTF-8을 사용하기 위해, 다음 C# 코드의 인코딩을 변경 :

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); 
    } 
} 

그리고 파이썬 코드 :

import base64 
s = base64.b64decode(data).decode('utf-8') 
message.ParseFromString(s) 
+0

이 오류가 발생합니다 : "문자열 인수가없는 인코딩 또는 오류" –

+0

아, 데이터가 문자열이 아니라 이미 bytearray가 될 수 있습니까? – Isma

+0

예. 그것은 바이트 배열입니다. –

관련 문제