我在我的.NET核心应用程序上编写了两个名为MakeHash
和CompareHash
的方法。现在有了MakeHash
,我可以成功地转换SHA1代码,但问题是我尝试比较哈希代码的方式总是返回false。这意味着CompareHash
方法不能比较普通代码和SHA1代码。你能告诉我如何修复CompareHash
,以便它能够在纯文本和SHA1散列代码之间进行比较?我在CompareHash
方法中做错了什么?提前感谢
public static string MakeHash(string str)
{
// generate a 128-bit salt using a secure PRNG
byte[] salt = new byte[128 / 8];
using (var rng = RandomNumberGenerator.Create())
{
rng.GetBytes(salt);
}
// derive a 256-bit subkey (use HMACSHA1 with 10,000 iterations)
string hashed = Convert.ToBase64String(KeyDerivation.Pbkdf2(
password: str,
salt: salt,
prf: KeyDerivationPrf.HMACSHA1,
iterationCount: 10000,
numBytesRequested: 256 / 8));
return hashed;
}
public static bool CompareHash(string plainString, string hashString)
{
if (MakeHash(plainString)==hashString)
{
return true;
}
else
{
return false;
}
}
发布于 2018-08-19 13:28:16
好吧,如果你需要一些快速的解决方案,而不需要在你的数据库中存储盐,那么你可以尝试使用下面的代码。这对我很有效。但强烈建议使用盐,并在它们之间进行匹配。因为它是关于安全性的,所以您应该小心,并在其中投入更多的精力。我的示例只是为您提供一个想法,而不是用于生产用途。
public static string MakeHash(string value)
{
return Convert.ToBase64String(
System.Security.Cryptography.SHA256.Create().ComputeHash(Encoding.UTF8.GetBytes(value))
);
}
public static bool CompareHash(string plainString, string hashString)
{
if (MakeHash(plainString) == hashString)
{
return true;
}
else
{
return false;
}
}
https://stackoverflow.com/questions/51914573
复制相似问题