简体   繁体   中英

How can I do hash and salt to manage secure credentials in C# with SQL Server 2008

I would like to know how can I do salting & hashing of passwords? I've found in Internet a lot of examples about it, but I still can't do it well.

I have this code to generate Salt and Hash

public static byte[] GetSalt()
{
    var p = new RNGCryptoServiceProvider();
    var salt = new byte[16];
    p.GetBytes(salt);
    return salt;    
}

public static byte [] GetSecureHash(string password, byte[] salt)
{
    Rfc2898DeriveBytes PBKDF2 = new Rfc2898DeriveBytes(password, salt);
    return PBKDF2.GetBytes(64);
}

But then, I don't know where I use these methods, I have this:

SqlParameter SalContraseña = new SqlParameter("@SalContraseña", SqlDbType.Binary, 16);
SalContraseña.Value = GetSalt();
cmd.Parameters.Add(SalContraseña);

SqlParameter HashContraseña = new SqlParameter("@HashContraseña",SqlDbType.Binary, 64);
HashContraseña.Value = GetSecureHash(Password,byte[]);
cmd.Parameters.Add(HashContraseña);

Here I apply the password and the hash to SqlParameter , but I'm not sure if it is correct or if this is the correct form to do this.

I applied these code in the form in which I create the users, then I don't know how apply this code to validate the passwords with the hash, I know I need to do this in the form in which the users are logged.

You would need to store the salt that you used to generate the original password hash. And then, when a user is attempting to log in, you retreive that salt value and hash the password they entered using the same hasing algorithm, and the same salt value originally used. If the resulting hash matches the stored user's hash, authentication is successful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM