c# - SHA1 hash code comparing fails
问题描述
I have written two method called-MakeHash
and CompareHash
on my .NET Core application. Now with MakeHash
I am able to successfully converting SHA1 code but the problem is the way I am trying to compare hash code is always returns false. That means the CompareHash
method is unable to compare plain code and SHA1 codes. Can you tell me how I can fix CompareHash
so it will able to compare between plain text and SHA1 hash code? What am I doing wrong in CompareHash
method? Thanks in advance
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;
}
}
解决方案
好吧,如果您需要一些快速解决方案而不在数据库中存储盐,那么您可以尝试使用下面的代码。这对我有用。但是强烈建议在它们之间使用盐和匹配。因为它是关于安全的,所以你应该小心并付出更多的努力。我的示例只是为您提供一个想法,而不是用于生产用途。
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;
}
}
推荐阅读
- python - 在 Pandas 中使用 groupby 函数时如何解决“keyerror”?
- java - 在Android中切换活动后无法单击按钮
- ruby-on-rails - 尝试更新时基本 CRUD 应用程序出错:ActiveRecord::StatementInvalid (SQLite3::SQLException: no such column:addresses.player_id)
- typescript - Vuex 共享操作
- c# - 如何显示来自 WinForms 项目的 toast 通知?
- core - Blazor - 可以在代码后面 NavigateTo 吗?
- python - 我不明白 kivymd 中的错误信息
- c - epoll 在包含数据的可用 fd 上设置 EPOLLHUP
- c++ - 我需要在基内存地址中为 [byte] 使用哪种数据类型?
- c# - 修复 SQL 参数化