如何验证存储在数据库中的密码作为哈希值?

时间:2013-01-23 07:38:27

标签: c# asp.net

我想以加密形式存储密码。我用过sha256。 我的代码如下

public static string ComputeHash(string plainText)
    {
        int minSaltSize = 4;
        int maxSaltSize = 8;

        Random random = new Random();
        int saltSize = random.Next(minSaltSize, maxSaltSize);

        byte[] saltBytes = new byte[saltSize];
        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
        rng.GetNonZeroBytes(saltBytes);

        byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
        byte[] plainTextWithSaltBytes = new byte[plainTextBytes.Length + saltBytes.Length];

        for (int i = 0; i < plainTextBytes.Length; i++)
            plainTextWithSaltBytes[i] = plainTextBytes[i];

        for (int i = 0; i < saltBytes.Length; i++)
            plainTextWithSaltBytes[plainTextBytes.Length + i] = saltBytes[i];


        HashAlgorithm hash = new SHA256Managed();
        byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes);
        byte[] hashWithSaltBytes = new byte[hashBytes.Length + saltBytes.Length];

        for (int i = 0; i < hashBytes.Length; i++)
            hashWithSaltBytes[i] = hashBytes[i];

        for (int i = 0; i < saltBytes.Length; i++)
            hashWithSaltBytes[hashBytes.Length + i] = saltBytes[i];

        string hashValue = Convert.ToBase64String(hashWithSaltBytes);
        return hashValue;
    }

现在,当用户登录时,我想验证此密码 我怎么能这样做?

1 个答案:

答案 0 :(得分:13)

从用户获取纯文本密码,使用相同的算法对其进行散列,并将新生成的散列与数据库中存储的散列进行比较。如果两个哈希值相同,则用户输入正确的密码。

更新

每次使用新鲜的盐,都会导致不同的哈希值。只需在数据库中创建一个包含所用盐的新列,然后选择此列。

将salt与哈希一起保存不是安全问题。如果直接使用盐,盐将仅禁止对单个散列算法使用预先计算的彩虹表。它没有提供任何关于使用的真实密码的线索,也没有提供关于如何将盐与纯文本密码(前置,附加,交织,...)结合的线索,因此可以安全地存储下一个生成的哈希。