Saving passwords for your application must be done with caution. Especialy when securing websites. Leaked databases have been exposed all over the internet.
In the event your database is exposed you want to make it as hard as possible to crack the passwords, so you have enought time to inform your users and let them change their passwords. Maybe event disable the users that haven’t changed their passwords.
I’ve written a util class that generates a salt and hashes strings (like passwords) with a salt. Using a salt to encrypt the password makes it hard to crack it. The salt is attached to the password and than the complete string is encrypted with the key. See below:
public static class SaltUtil { public static string GenerateRandomSalt() { // use Random Number Generator RNGCryptoServiceProvider algoritm = new RNGCryptoServiceProvider(); // request a byte array with random numbers of length 16 byte[] buff = new byte[16]; algoritm.GetBytes(buff); // return the string respresentation return Convert.ToBase64String(buff); } public static string GenerateSaltedHash(string password, string salt) { System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding(); // use SHA256 bit byte[] key = encoding.GetBytes("Your key here"); HashAlgorithm algorithm = new HMACSHA256(key); // combine password and salt byte[] combinedPasswordAndSalt = encoding.GetBytes(string.Concat(password, salt)); // compute the hash from password with salt byte[] hash = algorithm.ComputeHash(combinedPasswordAndSalt); // return the string representation return Convert.ToBase64String(hash); } }
On creation of a user you can generate a salt and hash the password. ! Make sure to save the salt as the code will generate a new salt every time !
Feel free to use this code and to comment on this below.