How to check the password stored in the database as a hash value?

I want to save the password in encrypted form. I used sha256. My code is below

public static string ComputeHash(string plainText) { int minSaltSize = 4; int maxSaltSize = 8; Random random = new Random(); int saltSize = random.Next(minSaltSize, maxSaltSize); byte[] saltBytes = new byte[saltSize]; RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); rng.GetNonZeroBytes(saltBytes); byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText); byte[] plainTextWithSaltBytes = new byte[plainTextBytes.Length + saltBytes.Length]; for (int i = 0; i < plainTextBytes.Length; i++) plainTextWithSaltBytes[i] = plainTextBytes[i]; for (int i = 0; i < saltBytes.Length; i++) plainTextWithSaltBytes[plainTextBytes.Length + i] = saltBytes[i]; HashAlgorithm hash = new SHA256Managed(); byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes); byte[] hashWithSaltBytes = new byte[hashBytes.Length + saltBytes.Length]; for (int i = 0; i < hashBytes.Length; i++) hashWithSaltBytes[i] = hashBytes[i]; for (int i = 0; i < saltBytes.Length; i++) hashWithSaltBytes[hashBytes.Length + i] = saltBytes[i]; string hashValue = Convert.ToBase64String(hashWithSaltBytes); return hashValue; } 

Now, when a user logs in, I want to confirm this password. How can I do this?

+4
source share
1 answer

Take a plaintext user password, hash it with the same algorithm, and compare the just created hash with the hash stored in the database. If both hashes are the same, the user enters the correct password.

Update

Each time you use fresh random salt, thousand, leading to different hashes. Just create a new column in your database containing salt and grab it.

It is not a security issue to save salt with a hash. Salt will prohibit the simple use of pre-calculated rainbow tables for a single hash algorithm if it is used directly. It does not give any information about the real password that was used, nor about how the salt is combined with the plaintext password (preend, append, inter-weaved, ...), so it can be safely stored as follows to the generated one hash.

+13
source

All Articles