Below is a very basic example of how to Hash using PBKDF2 with SHA512:
using System;
using System.Text;
using Security.Cryptography;
...
public string HashPassword(string pswd, string saltValue, long iterations)
{
byte[] pswdBytes = Encoding.UTF8.GetBytes(pswd);
byte[] saltByte = Encoding.UTF8.GetBytes(saltValue);
byte[] hashedPassword = null;
hashedPassword = BCryptPBKDF2.ComputeHash(PBKDF2HashAlgorithm.SHA512, pswdBytes, saltByte, iterations);
return Convert.ToBase64String(hashedPassword);
}
You can use it like this:
public void SaveNewUser(string username, string password)
{
string salt = GetSalt();
string hashedPassword = HashPassword(password, salt, 10000);
// Go save the username, hashed password and salt in the DB
SaveUserInDatabase(username, hashedPassword, salt);
}
public bool AuthenticateLogin(string username, string password)
{
// Get the salt saved from the DB for the user somehow
string salt = GetSaltFromDB(string username);
string hashedPassword = HashPassword(password, salt, 10000);
// Get the saved Password from database somehow
string savedPassword = GetSavedPasswordFromDB(string username);
if(hashedPassword.Equals(savedPassword))
{
return true;
}
return false;
}
When a new user is created, or how ever you initially save the password, SaveNewUser
is called to Salt, Hash and then save the password and the salt used.
Then when a user logs in, the entered password is again Salted (using the salt saved) and Hashed in AuthenticateUser
, but this time compared to the saved password. (Of course you need a way to get the same user from the database, but the concept remains the same.)
If the hashes match then the password match the user has entered in the correct password.
Read up on how to create a Salt value here.