Question

I am working on a project where we are using a custom user table. This table contains a password field. At the moment we save the plain text password into the database. what I want to ask is how do I save a hash of the password to the table instead? I have read about the Rfc2898DeriveBytes class but I don't know how to use this and how to generate salts and what the entire process is from start to finish.

Can you tell me what approach I might take?

Will each row in the user table need a salt value and if so where do I get this from?

Was it helpful?

Solution

You're on the right track with PBKDF2 / Rfc2898DeriveBytes. If you just need it for hashing passwords, have a look at SimpleCrypto.Net, which is basically a thin wrapper around Rfc2898DeriveBytes.

With SimpleCrypto.Net, you hash a user's password like this:

private ICryptoService cryptoService = new PBKDF2();

private void SetNewPassword(User user, string newPassword)
{
    //a new password hash is generated from a generated salt with the default settings
    user.Password = cryptoService.Compute(newPassword);
    //assigning the generated salt to the user
    user.PasswordSalt = cryptoService.Salt;
}

To check if a user entered the right password, you compute the hash with the same salt and compare it with the one you stored in your database:

private bool ValidatePassword(User user, string password)
{
    //hash the password with the saved salt for that user
    string hashed = cryptoService.Compute(password, user.PasswordSalt);
    //return true if both hashes are the same
    return hashed == user.Password;
}

Another possibility for securely hashing passwords is bcrypt. There is an implementation called BCrypt.Net.

OTHER TIPS

Storing the password in a plain-text field is not a good idea.

Please refer to : What is the best way to keep passwords configurable, without having them too easily available to the casual human reader?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top