我有一个字符串,需要对其进行哈希处理才能访问 API。 API 创建者在 Python 中提供了一个 codenippet,它对代码进行哈希处理,如下所示:
hashed_string = hashlib.sha1(string_to_hash).hexdigest()
当使用这个散列字符串访问 API 时,一切都很好。我尝试在 C# 中获得相同的哈希字符串结果,但没有成功。我尝试了很多方法,但到目前为止没有任何效果。我也知道十六进制消化部分,并且在尝试模仿该行为时我牢记这一点。
有谁知道如何在 C# 中得到相同的结果?
EDIT:这是我尝试在 C# 中重现相同结果的多种方法之一:
public string Hash(string input)
{
using (SHA1Managed sha1 = new SHA1Managed())
{
var hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(input));
var sb = new StringBuilder(hash.Length * 2);
foreach (byte b in hash)
{
sb.Append(b.ToString("X2"));
}
return sb.ToString().ToLower();
}
}
这段代码取自:在 C# 中使用 SHA1 算法进行哈希处理 https://stackoverflow.com/questions/17292366/hashing-with-sha1-algorithm-in-c-sharp
其他方式
public string ToHexString(string myString)
{
HMACSHA1 hmSha1 = new HMACSHA1();
Byte[] hashMe = new ASCIIEncoding().GetBytes(myString);
Byte[] hmBytes = hmSha1.ComputeHash(hashMe);
StringBuilder hex = new StringBuilder(hmBytes.Length * 2);
foreach (byte b in hmBytes)
{
hex.AppendFormat("{0:x2}", b);
}
return hex.ToString();
}
这段代码取自:Python hmac 和 C# hmac https://stackoverflow.com/questions/11790599/python-hmac-and-c-sharp-hmac
EDIT 2
一些输入/输出:
C#(使用上面描述中提供的第二种方法)
input: callerId1495610997apiKey3*_&E#N@B1)O)-1Y
output:1ecded2b66e152f0965adb96727d96b8f5db588a
Python
input: callerId1495610997apiKey3*_&E#N@B1)O)-1Y
output:bf11a12bbac84737a39152048e299fa54710d24e
C#(使用上面描述中提供的第一种方法)
input:callerId1495611935apiKey{[B{+%P)s;WD5&5x
output: 7e81e0d40ff83faf1173394930443654a2b39cb3
Python
input:callerId1495611935apiKey{[B{+%P)s;WD5&5x
output: 512158bbdbc78b1f25f67e963fefdc8b6cbcd741