如何在数据库中存储salted哈希密码

时间:2015-01-31 18:16:22

标签: c# asp.net

我试图想出一种方法来将盐渍哈希密码存储到我的数据库中。这是我第一次这样做,所以我有点不确定这个过程应该如何进行。

我的ASP.NET C#Web应用程序首先要求用户注册帐户。我有一个数据层,业务层来调用数据层中的方法,还有一个表示层来显示表单控件。目前,我使用纯文本将密码存储在数据库中。我们在数据层中调用该方法createAccount()。用户名,密码和其他属性将传递到createAccount()方法,以调用SQL查询来创建Account记录。用户名和密码由用户在注册页面中指定。我找到了一个网站,为我提供了一个使用哈希生成密码的方法,如下所示:

        public static string GenerateHashWithSalt(string password, string salt)
    {
        // merge password and salt together
        string sHashWithSalt = password + salt;
        // convert this merged value to a byte array
        byte[] saltedHashBytes = Encoding.UTF8.GetBytes(sHashWithSalt);
        // use hash algorithm to compute the hash
        System.Security.Cryptography.HashAlgorithm algorithm = new System.Security.Cryptography.SHA256Managed();
        // convert merged bytes to a hash as byte array
        byte[] hash = algorithm.ComputeHash(saltedHashBytes);
        // return the has as a base 64 encoded string
        return Convert.ToBase64String(hash);
    }

我应该在注册页面中的代码隐藏(.cs)页面或数据层中将它放在哪里?然后,你们怎么建议我把这个哈希密码和我的其他属性一起放在我的数据库中?我应该直接将其存储为散列,还是先将其存储在纯文本中,然后将其更新为散列值。谢谢!

1 个答案:

答案 0 :(得分:3)

我建议使用现有的实现,而不是在这里推广自己的实现。

asp.net membership数据库非常适用于此,uses salting and hashing out of the box