using System.Globalization; using System.Security.Cryptography; using System.Text; namespace Khaemhat.Infrastructure.Security; /// The result of checking a password against a stored hash. public enum PasswordVerification { /// The password does not match (or the hash is not readable). Failed = 0, /// The password matches. Succeeded = 1, /// The password matches, but the hash uses older parameters: store a new hash. SucceededRehashNeeded = 2, } /// /// Password hashes with PBKDF2-HMAC-SHA256 (SPEC ยง7.3): 600,000 iterations, a random 16-byte salt and a 32-byte /// result, stored as pbkdf2-sha256$600000$<salt base64>$<hash base64>. The comparison runs in /// constant time. /// public static class PasswordHasher { /// The algorithm prefix of the stored format. public const string Algorithm = "pbkdf2-sha256"; /// The iterations of new hashes (OWASP 2023 recommendation for PBKDF2-HMAC-SHA256). public const int Iterations = 600_000; private const int SaltLength = 16; private const int HashLength = 32; /// Hashes a password with a new random salt. /// The password. /// The stored form. public static string Hash(string password) => Hash(password, Iterations); /// Hashes a password with the given iterations (tests use fewer to stay fast). /// The password. /// The PBKDF2 iterations. /// The stored form. public static string Hash(string password, int iterations) { ArgumentNullException.ThrowIfNull(password); ArgumentOutOfRangeException.ThrowIfLessThan(iterations, 1); var salt = RandomNumberGenerator.GetBytes(SaltLength); var hash = Derive(password, salt, iterations); return string.Join('$', Algorithm, iterations.ToString(CultureInfo.InvariantCulture), Convert.ToBase64String(salt), Convert.ToBase64String(hash)); } /// Checks a password against a stored hash. /// The stored form; never matches. /// The password typed. /// The outcome. public static PasswordVerification Verify(string? storedHash, string password) { ArgumentNullException.ThrowIfNull(password); if (!TryParse(storedHash, out var iterations, out var salt, out var expected)) { return PasswordVerification.Failed; } var actual = Derive(password, salt, iterations, expected.Length); if (!CryptographicOperations.FixedTimeEquals(actual, expected)) { return PasswordVerification.Failed; } return iterations < Iterations ? PasswordVerification.SucceededRehashNeeded : PasswordVerification.Succeeded; } private static byte[] Derive(string password, byte[] salt, int iterations, int length = HashLength) { var bytes = Encoding.UTF8.GetBytes(password); try { return Rfc2898DeriveBytes.Pbkdf2(bytes, salt, iterations, HashAlgorithmName.SHA256, length); } finally { CryptographicOperations.ZeroMemory(bytes); } } private static bool TryParse(string? stored, out int iterations, out byte[] salt, out byte[] hash) { iterations = 0; salt = []; hash = []; var parts = stored?.Split('$'); if (parts is not { Length: 4 } || parts[0] != Algorithm || !int.TryParse(parts[1], NumberStyles.None, CultureInfo.InvariantCulture, out iterations) || iterations < 1) { return false; } try { salt = Convert.FromBase64String(parts[2]); hash = Convert.FromBase64String(parts[3]); } catch (FormatException) { return false; } return salt.Length >= 8 && hash.Length >= 16; } }