我对密码学还不熟悉,但是我需要使用HMACSHA256来传递信息。
我写了一个测试方法来测试我的散列方法。我使用在线生成器散列了这个单词: Paul和它们都有相同的base64值,但是当我使用下面的代码时,我得到了一个不同的值。我试着用不同的编码,但我无法得到价值,你能让我知道我可能哪里出错了吗?
[TestClass]
public class HashGeneratorUnitTest
{
[TestMethod]
public void TestMethod1()
{
string message = "Paul";
//Pass a string to method.
string hashedMessage = ShaGenerator.GetHash(message);
Assert.AreEqual("gYtcxfIdPm5OYHHAYpRSjURZUCIhhEbYt5ME0rdmMno=",
hashedMessage);
}
}
public static class ShaGenerator
{
public static string GetHash(string message, string secret = "")
{
var enc = new System.Text.ASCIIEncoding();
byte[] secretBytes = enc.GetBytes(secret);
byte[] messageBytes = enc.GetBytes(message);
using (var hmac = new HMACSHA256(secretBytes))
{
byte[] hashedBytes = hmac.ComputeHash(messageBytes);
string hashedString = Convert.ToBase64String(hashedBytes);
//Return HMACSHA256 string.
return hashedString; //returns: "g9gc9FI2RcI3N9ApYePF+si9Uh0p0Q4u2Vm0Wy5qphk="
}
}
}发布于 2014-02-19 01:17:12
https://stackoverflow.com/questions/21868634
复制相似问题