How to match HMACSHA256 between C# & Python

Things are rarely simple or obvious when working across languages; especially when one is .net.
Rather than waste time here's the code, in its long form.

Test parameters

With a key 182634d8894831d5dbce3b3185c50881
and a message or data value of some random junk
with both solutions we should receive d94ed997943420b7d5dfb9b31ae236b7b5225510d8f0314c54ad44fb5fd44a06

C#

public string HmacSHA256(string key, string data)  
{
    string hash;
    ASCIIEncoding encoder = new ASCIIEncoding();
    Byte[] code = encoder.GetBytes(key);
    using (HMACSHA256 hmac = new HMACSHA256(code))
    {
        Byte[] hmBytes = hmac.ComputeHash(encoder.GetBytes(data));
        hash = ToHexString(hmBytes);
    }
    return hash;
}

public static string ToHexString(byte[] array)  
{
    StringBuilder hex = new StringBuilder(array.Length * 2);
    foreach (byte b in array)
    {
        hex.AppendFormat("{0:x2}", b);
    }
    return hex.ToString();
}

Which will generate the same value for the same given inputs as:

Python 2.7/3

hmac.new(key.encode('utf-8'), data.encode('utf-8'), hashlib.sha256).hexdigest()  
Chris McKee

Chris McKee

https://chrismckee.co.uk

Software Engineer, Web Front/Backend/Architecture; all-round tech obsessed geek. I hate unnecessary optimism

View Comments