Python hmac和C#hmac
我们有一个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));
但是,我出来的结果不同了。
我应该改变散列的顺序吗?
谢谢,
乔恩
为了打印结果:
- 在Python中,您使用:
.hexdigest()
- 在C#中,您使用:
Convert.ToBase64String
这两个function根本不做同样的事情。 Python的hexdigest只是将字节数组转换为hex字符串,而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