C#: password storage with a salt and PBKDF2
Passwords must be stored so that a database leak does not reveal them. The recommended approach is a slow, salted password hash. The salt is a random value stored beside the hash. It makes equal passwords produce different hashes and defeats precomputed tables.
C#
using System;
using System.Security.Cryptography;
using System.Text;
class Program {
static byte[] Derive(string password, byte[] salt) {
return Rfc2898DeriveBytes.Pbkdf2(Encoding.UTF8.GetBytes(password), salt, 600000, HashAlgorithmName.SHA256, 32);
}
static void Main() {
byte[] salt = RandomNumberGenerator.GetBytes(16);
byte[] stored = Derive("correct horse", salt);
Console.WriteLine("hash length: " + stored.Length + " bytes");
Console.WriteLine("right password: " + CryptographicOperations.FixedTimeEquals(stored, Derive("correct horse", salt)));
Console.WriteLine("wrong password: " + CryptographicOperations.FixedTimeEquals(stored, Derive("wrong guess", salt)));
}
}