Password Hashing Implementation in C#
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Password Hashing runs in O(n) time and O(1) space, in C# as in every other language.
- ✓System.Security.Cryptography covers PBKDF2 through Rfc2898DeriveBytes, whose static one-shot Rfc2898DeriveBytes.Pbkdf2(password, salt, iterations, HashAlgorithmName.SHA256, outputLength) is the form to use; salts come from RandomNumberGenerator.GetBytes and comparison from CryptographicOperations.FixedTimeEquals.
- ✓The static Pbkdf2 method over constructing an Rfc2898DeriveBytes instance, and always an explicit HashAlgorithmName.
- ✓The C# trap: Rfc2898DeriveBytes is a byte stream, not a function. Calling GetBytes(32) twice on one instance returns two different 32-byte blocks because the second continues the PRF output, so a helper that derives once for storage and reuses the instance to verify never matches; Reset() restarts it.
- ✓Pbkdf2 has a Span<byte> overload that writes into a caller-supplied, usually stack-allocated destination, saving the heap allocation for the derived key on every login and keeping that key out of reach of a compacting GC that would otherwise copy it around memory.
What Password Hashing actually is
Password Hashing in C#: what you actually reach for
C# implementation
using System.Security.Cryptography;
using System.Text;
public static class Passwords
{
private const int Iterations = 210_000;
private const int SaltSize = 16;
private const int KeySize = 32;
public static string Hash(string password)
{
byte[] salt = RandomNumberGenerator.GetBytes(SaltSize);
byte[] key = Rfc2898DeriveBytes.Pbkdf2(
password.Normalize(NormalizationForm.FormKC),
salt, Iterations, HashAlgorithmName.SHA256, KeySize);
return $"pbkdf2-sha256${Iterations}${Convert.ToBase64String(salt)}" +
$"${Convert.ToBase64String(key)}";
}
public static bool Verify(string password, string stored)
{
string[] parts = stored.Split('$');
if (parts.Length != 4 || parts[0] != "pbkdf2-sha256") return false;
if (!int.TryParse(parts[1], out int iterations)) return false;
byte[] salt = Convert.FromBase64String(parts[2]);
byte[] expected = Convert.FromBase64String(parts[3]);
byte[] actual = Rfc2898DeriveBytes.Pbkdf2(
password.Normalize(NormalizationForm.FormKC),
salt, iterations, HashAlgorithmName.SHA256, expected.Length);
return CryptographicOperations.FixedTimeEquals(actual, expected);
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe C#-specific trap
Performance in C#, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which C# type or library should I use for Password Hashing?
System.Security.Cryptography covers PBKDF2 through Rfc2898DeriveBytes, whose static one-shot Rfc2898DeriveBytes.Pbkdf2(password, salt, iterations, HashAlgorithmName.SHA256, outputLength) is the form to use; salts come from RandomNumberGenerator.GetBytes and comparison from CryptographicOperations.FixedTimeEquals. ASP.NET Core ships Microsoft.AspNetCore.Identity.PasswordHasher<TUser>, a versioned PBKDF2 format whose cost is configured through PasswordHasherOptions.IterationCount and whose VerifyHashedPassword can return SuccessRehashNeeded. There is no bcrypt or Argon2 in the BCL: BCrypt.Net-Next and Konscious.Security.Cryptography.Argon2 are the ecosystem answers.
What is the most common C# mistake when implementing Password Hashing?
Rfc2898DeriveBytes is a byte stream, not a function. Calling GetBytes(32) twice on one instance returns two different 32-byte blocks because the second continues the PRF output, so a helper that derives once for storage and reuses the instance to verify never matches; Reset() restarts it. Separately, the constructor overloads that omit HashAlgorithmName default to HMAC-SHA1 and are now obsolete with a SYSLIB0041 diagnostic, so code pasted from older answers silently derives with SHA-1 while looking modern. The static Pbkdf2 method avoids both traps by construction.
How does Password Hashing actually perform in C#?
Pbkdf2 has a Span<byte> overload that writes into a caller-supplied, usually stack-allocated destination, saving the heap allocation for the derived key on every login and keeping that key out of reach of a compacting GC that would otherwise copy it around memory. The derivation itself calls the platform primitive, CNG on Windows and OpenSSL elsewhere, so per-iteration cost is native. The scaling caveat is ASP.NET-shaped: PBKDF2 has no async API, it is CPU-bound, and a login burst on the thread pool causes starvation, so bound concurrency instead of letting the pool grow. Time complexity is O(n) and space is O(1).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying full price for a tool, check the student deals on AI and developer tools listed on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.