首页 > 解决方案 > 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;
    }
}

标签: c#

解决方案


好吧,如果您需要一些快速解决方案而不在数据库中存储盐,那么您可以尝试使用下面的代码。这对我有用。但是强烈建议在它们之间使用盐和匹配。因为它是关于安全的,所以你应该小心并付出更多的努力。我的示例只是为您提供一个想法,而不是用于生产用途。

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;
            }
        }

推荐阅读