我正在使用这个页面为一些文本生成一些测试HMAC-SHA256散列:
https://www.liavaag.org/English/SHA-Generator/HMAC/
但是,当我尝试在我的.Net核心项目中使用this MSDN guide中的方法时,我得不到相同的结果。有人能给我解释一下如何在我的C#代码中获得与上一个网页相同的结果吗?
下面是我的代码:
// My own GetHash method usage:
var hashed = PasswordHelper.GetHash("Test", Encoding.UTF8.GetBytes("123"));
public static string GetHash(string password, byte[] salt)
{
// derive a 256-bit subkey (use HMACSHA1 with 10,000 iterations)
string hashed = Convert.ToBase64String(KeyDerivation.Pbkdf2(
password: password,
salt: salt,
prf: KeyDerivationPrf.HMACSHA256,
iterationCount: 10000,
numBytesRequested: 256 / 8));
return hashed;
}发布于 2017-12-07 10:50:12
使用以下方法:
public static String GetHash(String text, String key)
{
// change according to your needs, an UTF8Encoding
// could be more suitable in certain situations
ASCIIEncoding encoding = new ASCIIEncoding();
Byte[] textBytes = encoding.GetBytes(text);
Byte[] keyBytes = encoding.GetBytes(key);
Byte[] hashBytes;
using (HMACSHA256 hash = new HMACSHA256(keyBytes))
hashBytes = hash.ComputeHash(textBytes);
return BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
}您将获得与您提供的站点相同的结果:
Console.WriteLine(GetHash("qwerty","123456"));
// 3364ad93c083dc76d7976b875912442615cc6f7e3ce727b2316173800ca32b3a证明:

实际上,您使用的基于this tutorial和KeyDerivation.Pbkdf2的代码产生了不同的结果,因为它使用了复杂得多的参数化和另一种编码。但是,尽管结果不同,您仍然应该使用示例提供的方法,并坚持使用UTF8编码。
https://stackoverflow.com/questions/47686677
复制相似问题