2
저장소 해시 값으로 데이터베이스에 암호를 확인하는 방법
이 때문에 동일하지 않습니다 무작위로 소금을 생성합니다.
확인하고 테스트하기 위해 소금을 추가하는 방법.
다음은 해싱에 사용하는 코드이며 해시 된 암호를 확인합니다.
내 코드 :
/// <summary>
/// Generate the value from bytes.
/// </summary>
/// <param name="password"></param>
/// <param name="iterationCount"></param>
/// <returns></returns>
private static string GenerateHashValue(string password)
{
return Convert.ToBase64String(GenerateHashBytes(password));
}
/// <summary>
/// Hashing the password using PBKDF2
/// </summary>
/// <param name="password"></param>
/// <param name="iterationCount"></param>
/// <returns></returns>
private static byte[] GenerateHashBytes(string password)
{
byte[] hashValue;
//create salt
byte[] salt = GenerateRandomSalt();
var valueToHash = string.IsNullOrEmpty(password) ? string.Empty : password;
using (var pbkdf2 = new Rfc2898DeriveBytes(valueToHash,salt, iterationCount))
{
hashValue = pbkdf2.GetBytes(DerivedKeyLength);
}
return hashValue;
}
public static bool VerifyPassword(string password, string correctHash)
{
byte[] hash;
byte[] OriginalHash = Encoding.ASCII.GetBytes(correctHash);
hash = GenerateHashBytes(password);
return SlowEquals(hash, OriginalHash);
}
private static bool SlowEquals(byte[] a, byte[] b)
{
var diff = (uint)a.Length^(uint)b.Length;
for (int i = 0; i < a.Length && i < b.Length; i++)
{
diff |= (uint)(a[i]^b[i]);
}
return diff == 0;
}
/// <summary>
/// Used to generate the random string to append hash.
/// </summary>
/// <returns></returns>
private static byte[] GenerateRandomSalt()
{
/*We are using the RNGCryptoServiceProvider class to create a Cryptography Secure Pseudo-Random Number Generator that will generate the level of randomness and uniqueness we require for a salt.*/
var csprng = new RNGCryptoServiceProvider();
var salt = new byte[SaltByteLength];
csprng.GetBytes(salt);
return salt;
}