9

We have a python web service. It needs a hash as a parameter. The hash in python is generated this way.

    hashed_data = hmac.new("ant", "bat", hashlib.sha1)
    print hashed_data.hexdigest()

Now, this is how I generate the hash from C#.

    ASCIIEncoding encoder = new ASCIIEncoding();
    Byte[] code = encoder.GetBytes("ant");
    HMACSHA1 hmSha1 = new HMACSHA1(code);
    Byte[] hashMe = encoder.GetBytes("bat");
    Byte[] hmBytes = hmSha1.ComputeHash(hashMe);
    Console.WriteLine(Convert.ToBase64String(hmBytes));

However, I'm coming out with different result.

Should I change the order of the hashing?

Thank you,

Jon

2 Answers 2

22

In order to print the result:

  • In Python you use: .hexdigest()
  • In C# you use: Convert.ToBase64String

Those 2 functions don't do the same thing at all. Python's hexdigest simply converts the byte array to a hex string whereas the C# method uses Base64 encoding to convert the byte array. So to get the same output simply define a function:

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

and then:

ASCIIEncoding encoder = new ASCIIEncoding();
Byte[] code = encoder.GetBytes("ant");
HMACSHA1 hmSha1 = new HMACSHA1(code);
Byte[] hashMe = encoder.GetBytes("bat");
Byte[] hmBytes = hmSha1.ComputeHash(hashMe);
Console.WriteLine(ToHexString(hmBytes));

Now you will get the same output as in Python:

739ebc1e3600d5be6e9fa875bd0a572d6aee9266
Sign up to request clarification or add additional context in comments.

Comments

0

Instead of writing your own implementation to convert byte[] to a hex string, now you can get the same output as in Python using built in methods:

public static string ComputeHMACSHA256HexString(string key, string s)
{
    var hashValue = HMACSHA256.HashData(
        Encoding.UTF8.GetBytes(key),
        Encoding.UTF8.GetBytes(s));

    return BitConverter
        .ToString(hashValue)
        .Replace("-", "")
        .ToLower();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.