Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Password Hashing Implementation in C#

14 min readintermediate
Website QA and SEO audits

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 stores a login credential as a deliberately slow, salted, one-way derivation instead of the password itself. You verify by re-deriving with the stored salt and parameters and comparing in constant time. The cost parameters (iterations, memory, parallelism) exist to make offline cracking of a stolen table expensive. The modern choices are Argon2id, scrypt, bcrypt and PBKDF2 with a high iteration count. A plain SHA-256 or MD5 digest is not password hashing: a GPU computes billions of those per second. You reach for this the moment you own a users table with a password column, and again every few years when you raise the cost and rehash on next login.

Password Hashing in C#: what you actually reach for

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.

C# implementation

The static Pbkdf2 method over constructing an Rfc2898DeriveBytes instance, and always an explicit HashAlgorithmName. FixedTimeEquals rather than SequenceEqual, == or a manual loop. The iteration count and format version belong in the stored string. If the project already uses Identity, reviewers expect PasswordHasher<TUser> and expect SuccessRehashNeeded to be acted on rather than treated as plain success, because that is the only automatic upgrade path Identity offers.
csharp
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 Free

The C#-specific 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. 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.

Performance in C#, beyond the O(n)

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. The asymptotic cost is the same in every language, O(n) time and O(1) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Password Hashing between languages.

Real-World Applications

Password Hashing is used extensively in production software: authentication systems, payment processing, encrypted communications, and data protection mechanisms depend on this technique. In C#, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Password Hashing helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Password Hashing appears frequently in onsite coding rounds at mid-to-large tech companies. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Password Hashing over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Password Hashing to build pattern recognition. In C#, demonstrate proficiency with LINQ and async patterns to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic C# code that is both correct and maintainable.

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).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

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 trial

Before paying full price for a tool, check the student deals on AI and developer tools listed on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

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.