Python hmac和C# hmac

8
我们有一个Python Web服务。它需要一个哈希作为参数。 在Python中,哈希是这样生成的。
    hashed_data = hmac.new("ant", "bat", hashlib.sha1)
    print hashed_data.hexdigest()

现在,我来介绍一下如何在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));

然而,我的结果与之前不同。

我是否应该改变哈希的顺序?

谢谢,

Jon

1个回答

21
为了打印结果,你可以这样做:
  • 在Python中使用:.hexdigest()
  • 在C#中使用:Convert.ToBase64String
这两个函数完全不同。Python的hexdigest函数只是将字节数组转换为十六进制字符串,而C#方法使用Base64编码将字节数组转换。因此,为了得到相同的输出,只需定义一个函数:
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();
}

然后:

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

现在你将获得与Python相同的输出:

739ebc1e3600d5be6e9fa875bd0a572d6aee9266

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接