【发布时间】:2017-10-03 10:26:35
【问题描述】:
我想知道是否有使用密钥生成 SHA256 哈希的标准代码。我遇到过几种类型的代码,但是,它们不会产生相同的输出。
代码位于JokeCamp
private string CreateToken(string message, string secret)
{
secret = secret ?? "";
var encoding = new System.Text.ASCIIEncoding();
byte[] keyByte = encoding.GetBytes(secret);
byte[] messageBytes = encoding.GetBytes(message);
using (var hmacsha256 = new HMACSHA256(keyByte))
{
byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
return Convert.ToBase64String(hashmessage);
}
}
这是我找到的另一个
private static string ComputeHash(string apiKey, string message)
{
var key = Encoding.UTF8.GetBytes(apiKey);
string hashString;
using (var hmac = new HMACSHA256(key))
{
var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(message));
hashString = Convert.ToBase64String(hash);
}
return hashString;
}
这两者生成的代码与http://www.freeformatter.com/hmac-generator.html#ad-output生成的代码不同
我将SHA256 用于我们的一个外部API,消费者将在其中散列数据并将其发送给我们。所以我们只想确保我们使用标准方法,以便他们向我们发送正确的哈希值。另外,我想知道是否有任何知名的 nugets 。我也尝试使用 Bouncy Castle 找到解决方案,但是,我找不到使用密钥进行散列的解决方案。
【问题讨论】: