|
| 1 | +public class Test |
| 2 | +{ |
| 3 | + private const int SaltSize = 32; |
| 4 | + |
| 5 | + // BAD - Hash without a salt. |
| 6 | + public static String HashPassword(string password, string strAlgName ="SHA256") |
| 7 | + { |
| 8 | + IBuffer passBuff = CryptographicBuffer.ConvertStringToBinary(password, BinaryStringEncoding.Utf8); |
| 9 | + HashAlgorithmProvider algProvider = HashAlgorithmProvider.OpenAlgorithm(strAlgName); |
| 10 | + IBuffer hashBuff = algProvider.HashData(passBuff); |
| 11 | + return CryptographicBuffer.EncodeToBase64String(hashBuff); |
| 12 | + } |
| 13 | + |
| 14 | + // GOOD - Hash with a salt. |
| 15 | + public static string HashPassword2(string password, string salt, string strAlgName ="SHA256") |
| 16 | + { |
| 17 | + // Concatenate the salt with the password. |
| 18 | + IBuffer passBuff = CryptographicBuffer.ConvertStringToBinary(password+salt, BinaryStringEncoding.Utf8); |
| 19 | + HashAlgorithmProvider algProvider = HashAlgorithmProvider.OpenAlgorithm(strAlgName); |
| 20 | + IBuffer hashBuff = algProvider.HashData(passBuff); |
| 21 | + return CryptographicBuffer.EncodeToBase64String(hashBuff); |
| 22 | + } |
| 23 | + |
| 24 | + // BAD - Hash without a salt. |
| 25 | + public static string HashPassword(string password) |
| 26 | + { |
| 27 | + SHA256 sha256Hash = SHA256.Create(); |
| 28 | + byte[] passBytes = System.Text.Encoding.ASCII.GetBytes(password); |
| 29 | + byte[] hashBytes = sha256Hash.ComputeHash(passBytes); |
| 30 | + return Convert.ToBase64String(hashBytes); |
| 31 | + } |
| 32 | + |
| 33 | + // GOOD - Hash with a salt. |
| 34 | + public static string HashPassword2(string password) |
| 35 | + { |
| 36 | + byte[] passBytes = System.Text.Encoding.ASCII.GetBytes(password); |
| 37 | + byte[] saltBytes = GenerateSalt(); |
| 38 | + |
| 39 | + // Add the salt to the hash. |
| 40 | + byte[] rawSalted = new byte[passBytes.Length + saltBytes.Length]; |
| 41 | + passBytes.CopyTo(rawSalted, 0); |
| 42 | + saltBytes.CopyTo(rawSalted, passBytes.Length); |
| 43 | + |
| 44 | + //Create the salted hash. |
| 45 | + SHA256 sha256 = SHA256.Create(); |
| 46 | + byte[] saltedPassBytes = sha256.ComputeHash(rawSalted); |
| 47 | + |
| 48 | + // Add the salt value to the salted hash. |
| 49 | + byte[] dbPassword = new byte[saltedPassBytes.Length + saltBytes.Length]; |
| 50 | + saltedPassBytes.CopyTo(dbPassword, 0); |
| 51 | + saltBytes.CopyTo(dbPassword, saltedPassBytes.Length); |
| 52 | + |
| 53 | + return Convert.ToBase64String(dbPassword); |
| 54 | + } |
| 55 | + |
| 56 | + public static byte[] GenerateSalt() |
| 57 | + { |
| 58 | + using (var rng = new RNGCryptoServiceProvider()) |
| 59 | + { |
| 60 | + var randomNumber = new byte[SaltSize]; |
| 61 | + rng.GetBytes(randomNumber); |
| 62 | + return randomNumber; |
| 63 | + } |
| 64 | + } |
| 65 | +} |
0 commit comments