Recipe 7.1 · C#
Password Hashing with PBKDF2
Problem
Passwords are stored in plain text, encrypted with a reversible key, or hashed with a fast algorithm such as MD5 or SHA-1, often without a salt. When the database leaks (a backup on a file share, a developer's copy, a SQL injection), every password can be recovered in hours with commodity hardware, and many of your users reuse them elsewhere.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
// Not this: fast, unsalted, and broken for passwords.
public static string HashPassword(string password)
{
using (MD5 md5 = MD5.Create())
{
byte[] bytes = md5.ComputeHash(Encoding.UTF8.GetBytes(password));
return BitConverter.ToString(bytes).Replace("-", "");
}
}
public static bool Check(string password, string stored) =>
HashPassword(password) == stored;
The improved recipe
Use PBKDF2 with HMAC-SHA-256, a random salt per password, a high iteration count and a self-describing storage format. Compare in constant time, and tell the caller when a stored hash should be upgraded.
using System;
using System.Globalization;
using System.Security.Cryptography;
namespace ImproveCode.Security;
public enum PasswordVerification
{
Failed,
Success,
SuccessRehashNeeded
}
public static class Pbkdf2PasswordHasher
{
private const string Scheme = "pbkdf2-sha256";
private const int SaltSize = 16; // 128 bits
private const int HashSize = 32; // 256 bits
private const int Iterations = 600_000;
private static readonly HashAlgorithmName Algorithm =
HashAlgorithmName.SHA256;
/// <summary>Returns "pbkdf2-sha256$iterations$salt$hash".</summary>
public static string Hash(string password)
{
ArgumentException.ThrowIfNullOrEmpty(password);
byte[] salt = RandomNumberGenerator.GetBytes(SaltSize);
byte[] hash = Rfc2898DeriveBytes.Pbkdf2(
password, salt, Iterations, Algorithm, HashSize);
return string.Join('$',
Scheme,
Iterations.ToString(CultureInfo.InvariantCulture),
Convert.ToBase64String(salt),
Convert.ToBase64String(hash));
}
public static PasswordVerification Verify(
string password, string storedHash)
{
ArgumentNullException.ThrowIfNull(password);
ArgumentNullException.ThrowIfNull(storedHash);
string[] parts = storedHash.Split('$');
if (parts.Length != 4 || parts[0] != Scheme
|| !int.TryParse(parts[1], NumberStyles.None,
CultureInfo.InvariantCulture, out int iterations)
|| iterations < 1)
{
return PasswordVerification.Failed;
}
byte[] salt;
byte[] expected;
try
{
salt = Convert.FromBase64String(parts[2]);
expected = Convert.FromBase64String(parts[3]);
}
catch (FormatException)
{
return PasswordVerification.Failed;
}
byte[] actual = Rfc2898DeriveBytes.Pbkdf2(
password, salt, iterations, Algorithm, expected.Length);
if (!CryptographicOperations.FixedTimeEquals(actual, expected))
{
return PasswordVerification.Failed;
}
return iterations < Iterations
? PasswordVerification.SuccessRehashNeeded
: PasswordVerification.Success;
}
}
If you already use ASP.NET Core Identity, or want a hasher maintained by Microsoft, use its
PasswordHasher<TUser> from the Microsoft.Extensions.Identity.Core package. It works without
the rest of Identity:
using Microsoft.AspNetCore.Identity;
namespace ImproveCode.Security;
public sealed class AppUser
{
public string UserName { get; set; } = string.Empty;
public string PasswordHash { get; set; } = string.Empty;
}
public sealed class UserPasswords(IPasswordHasher<AppUser> hasher)
{
public void SetPassword(AppUser user, string password) =>
user.PasswordHash = hasher.HashPassword(user, password);
/// <summary>Returns true when the password is correct. Upgrades
/// the stored hash when the hasher asks for it; the caller
/// saves the user afterwards.</summary>
public bool Verify(AppUser user, string password)
{
PasswordVerificationResult result =
hasher.VerifyHashedPassword(
user, user.PasswordHash, password);
if (result == PasswordVerificationResult.SuccessRehashNeeded)
{
SetPassword(user, password);
}
return result != PasswordVerificationResult.Failed;
}
}
Register it once, as a usage snippet:
builder.Services.AddSingleton<
IPasswordHasher<AppUser>, PasswordHasher<AppUser>>();
builder.Services.AddSingleton<UserPasswords>();
How it works
PBKDF2 runs HMAC-SHA-256 hundreds of thousands of times. That costs a fraction of a second for one login, which nobody notices, and makes each guess in an offline attack equally expensive. The 600,000 iterations follow current OWASP guidance for PBKDF2-HMAC-SHA-256. MD5, by contrast, can be computed billions of times per second on one graphics card.
The random salt makes every stored hash unique, even for two users with the same password, so precomputed tables are useless and each account must be attacked separately.
The storage string records the scheme, iteration count, salt and hash. That is what makes the
format upgradeable. When you raise Iterations next year, existing hashes still verify with the
count they were created with, Verify returns SuccessRehashNeeded, and the login code stores a
fresh hash while it has the plain password in hand. Over a few months the whole user table moves
to the new cost without a forced reset.
CryptographicOperations.FixedTimeEquals compares every byte regardless of where the first
difference is. A normal == or SequenceEqual returns early, which in principle leaks how much
of the hash matched through timing.
The Identity hasher does the same job with its own versioned format (PBKDF2 with HMAC-SHA-512 and
100,000 iterations by default since .NET 7, configurable through PasswordHasherOptions). It also
returns SuccessRehashNeeded, so the upgrade path is identical.
Variations and pitfalls
- Migrating from MD5 or SHA-1: don't wait for users to log in. Wrap each old hash immediately by
computing
Pbkdf2(oldHash)and storing it with a different scheme name, then replace it with a normal hash at the next successful login. The weak hashes are gone from the database on day one. - Argon2id is the other strong choice, through a third-party package. PBKDF2 is in the base class library, FIPS-approved and good enough when the iteration count is high.
- Hashing is CPU-heavy by design. Rate-limit login attempts (ASP.NET Core's rate-limiting middleware does this), or an attacker can use your login page to burn your CPU.
- Never log the password, even on failure, and never return different errors for "unknown user" and "wrong password."
- The column needs room. The PBKDF2 string here is under 100 characters;
NVARCHAR(256)leaves space for future schemes.