如何在 .Net Core 中生成 HMAC-SHA256?
How to generate HMAC-SHA256 in .Net Core?
我正在使用此页面为某些文本生成一些测试 HMAC-SHA256 哈希值:
https://www.liavaag.org/English/SHA-Generator/HMAC/
但是,当我尝试在我的 .Net Core 项目中使用 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;
}
使用以下方法:
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
编码。
我正在使用此页面为某些文本生成一些测试 HMAC-SHA256 哈希值:
https://www.liavaag.org/English/SHA-Generator/HMAC/
但是,当我尝试在我的 .Net Core 项目中使用 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;
}
使用以下方法:
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
编码。