Python and C# HMAC SHA1 results are not Matching

103 views Asked by At
import hashlib
import hmac
import base64
import json


def make_digest(payload, api_key,api_secret):

    api_key = api_key.encode("ascii")
    api_secret = api_secret.encode("ascii")
    payload = payload.encode("ascii")

    # print(payload)
    k=b'%s&%s' % (api_key, api_secret)

    signature = hmac.new(
    key= k,
    msg=payload,
    digestmod=hashlib.sha1)

    signature_digest = signature.digest()

    return base64.b64encode(signature_digest)


api_key='somekey'
api_secret='somesecret'

payload1 = "{\"name\":\"somename\",\"filter_type\":\"somefilter\",\"filter_id\":\"1\",\"event_type\":\"some_event\",\"event_id\":\"1\",\"event_datetime\":\"2023-02-20T13:07:26.367367+00:00\",\"object_type\":\"sometype\",\"object_id\":\"2\",\"resources\":{\"respondent_id\":\"12\",\"recipient_id\":\"0\",\"survey_id\":\"12313\",\"user_id\":\"12312312313\",\"collector_id\":\"234234\"}}"


payload=json.loads(payload1)

payload=json.dumps(payload)
result = make_digest(payload,api_key,api_secret)
print(result)
result1 = make_digest(payload1,api_key,api_secret)
print(result1)

I am a dotnet dev, currently exporting a Python function to C# .net 6. I am not able to get the same output in C#.

public static string GetHash(string apiKey,string apiSecret, string payLoad)
{
    ASCIIEncoding encoding = new ASCIIEncoding();

    byte[] apiSecretAscii = encoding.GetBytes(apiSecret);
    byte[] apiKeyAscii = encoding.GetBytes(apiKey);
    byte[] payLoadBytes = encoding.GetBytes(payLoad);
    byte[] hashBytes;
    var key = apiKeyAscii.Concat(encoding.GetBytes("&")).Concat(apiSecretAscii).ToArray();
    using (HMACSHA1 hash = new (key))
    {
        hashBytes = hash.ComputeHash(payLoadBytes);
    }

    return Convert.ToBase64String(hashBytes);
}

And calling this function like this

 var str = GetHash("somekey", "somesecret", "{\"name\":\"somename\",\"filter_type\":\"somefilter\",\"filter_id\":\"1\",\"event_type\":\"some_event\",\"event_id\":\"1\",\"event_datetime\":\"2023-02-20T13:07:26.367367+00:00\",\"object_type\":\"sometype\",\"object_id\":\"2\",\"resources\":{\"respondent_id\":\"12\",\"recipient_id\":\"0\",\"survey_id\":\"12313\",\"user_id\":\"12312312313\",\"collector_id\":\"234234\"}}");
            Console.WriteLine(str);

I have few questions regarding this:

  1. I am not sure why the first print output of the Python code is not similar to second print output of the Python code. I want to match the first outcome of the Python code in the C# code. Basically this hash needs to be matched which I am getting from request header for the same request.
  2. Is json.dumps in Python the equivalent of NewtonSoft.Jsonconvert.SerializeObject()?
0

There are 0 answers