我们有一个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));然而,我得出了不同的结果。
我应该改变散列的顺序吗?
谢谢,
琼恩
发布于 2012-08-03 15:02:25
要打印结果:
在Python语言中使用:.hexdigest()
Convert.ToBase64String这两个函数做的事情完全不一样。Python十六进制只是将字节数组转换为十六进制字符串,而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中相同的输出:
739ebc1e3600d5be6e9fa875bd0a572d6aee9266https://stackoverflow.com/questions/11790599
复制相似问题