Reputation: 1533
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;
}
}
Upvotes: 1
Views: 546
Reputation: 1384
Well, if you need some quick solution without storing salt on your database then you can give a try with the code below. This works for me. But this is highly recommended to use salt and match between them. Because it's about security you should be careful and put some more effort into it. My example is just to provide you an idea, not for production usage.
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;
}
}
Upvotes: 1