我们有一个 python 网络服务。它需要一个哈希作为参数。
python中的hash就是这样生成的。
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
为了打印结果:
- 在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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)