📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How should an ASP.NET Core application store user passwords? Explain salts, peppers and work factors, compare PBKDF2, bcrypt and Argon2id, describe what Identity's PasswordHasher does, and how you would upgrade a database of old SHA-1 or MD5 hashes without forcing every user to reset.

Covers secure password storage: per-user salts, optional pepper, tunable work factors, PBKDF2 vs bcrypt vs Argon2id, Identity's versioned PasswordHasher and migrating legacy hashes by wrapping and rehash-on-login.

Intermediate Security Intermediate argon2 aspnet-core-identity cryptography password-hashing pbkdf2 security

🎯 Key points

  • Per-user random salt (16+ bytes) stored with the hash defeats rainbow tables
  • Work factor tuned to roughly 50-250 ms per hash on production hardware
  • OWASP guidance: Argon2id (19 MiB, t=2, p=1) first; PBKDF2-HMAC-SHA512 about 210,000 iterations where FIPS matters
  • Identity PasswordHasher V3: PBKDF2-HMAC-SHA512, 100,000 iterations by default since .NET 7, versioned format, SuccessRehashNeeded
  • Pepper: a secret in Key Vault applied as HMAC, rotation needs a version id
  • Legacy migration: wrap old hashes (PBKDF2(MD5(pw))) immediately, then rehash on next login
  • Constant-time verification and login rate limiting / lockout

⏱ 30-second answer

Never store the password or a fast hash of it. Store the output of a slow, salted password hashing function: a random salt per user (so identical passwords differ and rainbow tables fail) and a work factor that makes each guess cost tens of milliseconds. For new systems OWASP recommends Argon2id because it is memory-hard; where FIPS 140 validation is required, PBKDF2-HMAC-SHA512 is the right choice, and it is what ASP.NET Core Identity's PasswordHasher<TUser> uses (100,000 iterations by default since .NET 7, raisable, versioned so old hashes keep verifying). An optional pepper kept in Key Vault means a database-only leak isn't enough.

To fix a legacy MD5 or SHA-1 table, wrap every old hash now (PBKDF2(oldHash)) and rehash on next successful login. Hashing only protects you after a breach, so pair it with lockout and rate limiting on login. The trade-off is login CPU versus attacker cost.

🗣 Full answer (senior)

How I would answer this in an interview

"The threat model is an offline attack after a breach: the attacker has the table and guesses passwords as fast as their hardware allows. So storage has three jobs. A per-user random salt so each guess only tests one account and rainbow tables are useless. A work factor so each guess is slow: I aim for something like 50 to 250 milliseconds on our production hardware. And ideally memory hardness, so GPUs and ASICs don't get a huge advantage. That points to Argon2id, with PBKDF2-HMAC-SHA512 at a high iteration count when we need FIPS-validated primitives, and bcrypt as an acceptable legacy choice with its 72-byte input limit.

In ASP.NET Core I start with Identity's PasswordHasher<TUser>. It writes a versioned string: format marker, PRF, iteration count, salt and subkey. Today that is PBKDF2 with HMAC-SHA512 and 100,000 iterations, and because the count is stored in the hash I can raise PasswordHasherOptions.IterationCount and old hashes still verify. VerifyHashedPassword returns SuccessRehashNeeded and Identity's SignInManager rehashes for me. If I want Argon2id I implement IPasswordHasher<TUser> and keep verifying the old format.

For example, at [company] we inherited [a membership table with unsalted SHA-1 for about 300,000 users]. I didn't wait for logins: in one migration we computed PBKDF2(SHA1hash) for every row and tagged it as version 'wrapped', so nothing weak was left at rest the same day. Then on each successful login we verified through the wrapper and rehashed the plain password natively. [Within 60 days roughly 70%] were native; the rest got a forced reset email.

The mistake I see is focusing on the algorithm and forgetting the rest: no lockout or rate limiting on login, hashes compared with ==, or passwords leaking into logs before they're ever hashed. Strong hashing buys time after a breach; it doesn't stop online guessing."


Algorithm comparison

Algorithm Strength Weakness Suggested parameters (OWASP Password Storage Cheat Sheet)
Argon2id Memory-hard, GPU-resistant Not in the BCL, needs a vetted package m = 19 MiB, t = 2, p = 1 (or more memory)
scrypt Memory-hard Less common in .NET N = 2^17, r = 8, p = 1
bcrypt Battle-tested, simple 72-byte input limit, not memory-hard cost 10 or more
PBKDF2-HMAC-SHA512 FIPS-validated, in the BCL Not memory-hard, needs high iterations about 210,000 iterations
SHA-x / MD5 (even salted) Fast Fast Never

Salt vs pepper

Salt Pepper
Secret? No, stored beside the hash Yes, in Key Vault or an HSM
Unique? Per password Per application (versioned)
Defends against Rainbow tables, parallel cracking A database-only leak (SQL injection, backup theft)
Cost None Key management and rotation complexity

The vulnerable code, the attack and the fix

  • Vulnerable: user.PasswordHash = Convert.ToHexString(SHA1.HashData(Encoding.UTF8.GetBytes(password)));
  • Attack in one line: the attacker downloads the table and runs a wordlist through a GPU cracker at billions of SHA-1 guesses per second.
  • Fixed: user.PasswordHash = passwordHasher.HashPassword(user, password); plus lockout and rate limiting on the login endpoint.

Australian context

A password table leak is very likely an eligible data breach under the Notifiable Data Breaches scheme, and APP 11 requires "reasonable steps" to protect personal information. Weak hashing makes "serious harm is unlikely" impossible to argue.

Production example

Raising PBKDF2 from [10,000 to 210,000] iterations moved our verify time from [about 4 ms to about 80 ms] on [B2s App Service instances]. Login p95 went up [70 ms], which nobody noticed, and we added a fixed-window rate limiter of [5 attempts per minute per account and IP] so the extra CPU couldn't be used as a DoS lever.

🔍 What the interviewer is checking

Checks whether the candidate can design password storage end to end, including parameters, upgrade paths and the online-attack side.

Green flags

  • Explains salt and work factor in terms of attacker cost
  • Names Argon2id/PBKDF2/bcrypt with sensible parameters and knows Identity's defaults
  • Describes wrapping legacy hashes and rehash-on-login
  • Mentions lockout, rate limiting and MFA alongside hashing

Red flags

  • Suggests encryption or a single fast hash
  • Believes the salt must be secret
  • No plan for existing users other than "force everyone to reset"

📚 Learn in depth

1. The economics

The defender pays the work factor once per login; the attacker pays it once per guess per account.

Cost to crack one account = (guesses needed) x (time per hash) / (attacker's parallel units)
                                                   ^ you control this

Raise the time per hash 1,000x and you raise the attacker's cost 1,000x while your login gets maybe 50 ms slower.

2. Why memory hardness matters

PBKDF2 is just HMAC repeated N times. A GPU has thousands of cores with little memory each, so it parallelises PBKDF2 well. Argon2id fills a large memory block (e.g. 19 MiB) and reads it in a data-dependent pattern, so each guess needs that memory: the GPU can run far fewer guesses at once.

3. Inside Identity's hash format

byte 0      : 0x01  (V3 format marker)
bytes 1-4   : PRF (KeyDerivationPrf: 2 = HMACSHA512)
bytes 5-8   : iteration count (big-endian)
bytes 9-12  : salt length (16)
bytes 13-28 : salt
bytes 29-60 : derived subkey (32 bytes)
-> Base64 encoded into AspNetUsers.PasswordHash

VerifyHashedPassword reads the parameters from the stored hash, recomputes, compares with CryptographicOperations.FixedTimeEquals, and returns SuccessRehashNeeded when the stored iteration count or PRF is below the current options. V2 hashes (PBKDF2-SHA1, 1,000 iterations, from ASP.NET Identity 2) still verify when CompatibilityMode allows it, and get upgraded.

4. Peppering correctly

Apply the pepper as an HMAC before the slow hash: Argon2id(HMACSHA256(pepper, password), salt). Store a pepper version with each hash so you can rotate: new hashes use v2, old ones verify with v1 and are rehashed on login. Never just concatenate, and never put the pepper in the same database.

5. Migrating legacy hashes

Day 0  : every row  -> hash = PBKDF2(legacyHash, newSalt), format = "wrapped-sha1"
Login  : verify PBKDF2(SHA1(input), salt) == hash
         on success -> hash = native(input), format = "v3"
Day 90 : remaining wrapped rows -> force reset, then delete the format

Wrapping removes the weak hash from storage immediately, which matters if the breach happens before users log in.

6. The online side

Offline cracking is half the story. Credential stuffing uses passwords leaked elsewhere. Defences: lockout (LockoutOptions), ASP.NET Core rate limiting, checking new passwords against known-breached lists (k-anonymity range queries to Have I Been Pwned), and MFA.

Try it yourself

  1. Benchmark PasswordHasher<object>.HashPassword at 100,000, 210,000 and 600,000 iterations with BenchmarkDotNet on your laptop and on a small cloud VM.
  2. Decode an Identity hash from Base64 and read the PRF, iteration count and salt bytes by hand.
  3. Raise IterationCount, log in with an old account, and confirm the PasswordHash column changes.
  4. Write a custom IPasswordHasher<TUser> that verifies a wrapped-sha1 format and returns SuccessRehashNeeded.
  5. Add a rate limiter to the login endpoint and watch it reject the 6th attempt with 429.

💻 Code

Raising Identity's work factor, and a hasher that upgrades wrapped legacy SHA-1 hashes on login.

// Program.cs
builder.Services.Configure<PasswordHasherOptions>(o =>
{
    o.CompatibilityMode = PasswordHasherCompatibilityMode.IdentityV3;
    o.IterationCount = 210_000; // stored in each hash, so raising it is safe
});
builder.Services.AddScoped<IPasswordHasher<AppUser>, LegacyAwarePasswordHasher>();
using System.Security.Cryptography;
using System.Text;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Options;

namespace Accounts.Security;

public sealed class AppUser : IdentityUser;

// Legacy rows were migrated on day 0 to: "wrapped-sha1$<base64 salt>$<base64 PBKDF2(SHA1(pw))>"
public sealed class LegacyAwarePasswordHasher(IOptions<PasswordHasherOptions> options)
    : IPasswordHasher<AppUser>
{
    private const string WrappedPrefix = "wrapped-sha1$";
    private readonly PasswordHasher<AppUser> _inner = new(options);

    public string HashPassword(AppUser user, string password) => _inner.HashPassword(user, password);

    public PasswordVerificationResult VerifyHashedPassword(AppUser user, string hashedPassword, string providedPassword)
    {
        if (!hashedPassword.StartsWith(WrappedPrefix, StringComparison.Ordinal))
            return _inner.VerifyHashedPassword(user, hashedPassword, providedPassword);

        var parts = hashedPassword[WrappedPrefix.Length..].Split('$');
        byte[] salt = Convert.FromBase64String(parts[0]);
        byte[] expected = Convert.FromBase64String(parts[1]);

        byte[] legacy = SHA1.HashData(Encoding.UTF8.GetBytes(providedPassword)); // the old weak step
        byte[] actual = Rfc2898DeriveBytes.Pbkdf2(legacy, salt, 210_000, HashAlgorithmName.SHA512, expected.Length);

        // Constant time, then ask Identity to store a native V3 hash.
        return CryptographicOperations.FixedTimeEquals(actual, expected)
            ? PasswordVerificationResult.SuccessRehashNeeded
            : PasswordVerificationResult.Failed;
    }
}

⚠ Common mistakes

  • Mistake: Salting a fast hash (SHA256(salt + password)) and calling it done. Why it is wrong: the salt stops rainbow tables, but each guess is still nanoseconds. Instead: use a slow KDF with a tuned work factor.
  • Mistake: Relying on strong hashing alone, with no lockout or rate limiting on login. Why it is wrong: hashing only slows offline cracking; online guessing and credential stuffing hit the live endpoint. Instead: enable Identity LockoutOptions (e.g. 5 failures, 15 minutes), add an ASP.NET Core rate limiter per account and IP, and offer MFA.
  • Mistake: Copying an iteration count from a 2012 blog post. Why it is wrong: hardware got thousands of times faster. Instead: follow current OWASP guidance and benchmark on your hardware.
  • Mistake: Choosing Argon2id in a system that must use FIPS-validated cryptography. Why it is wrong: Argon2 is not a FIPS-approved algorithm, which can fail a compliance assessment. Instead: PBKDF2-HMAC-SHA512 with a high iteration count.
  • Mistake: Waiting for users to log in before upgrading legacy hashes. Why it is wrong: inactive accounts keep weak hashes at rest indefinitely. Instead: wrap every legacy hash immediately, then rehash on login.
  • Mistake: Storing the pepper in the same database or appsettings.json. Why it is wrong: the leak that exposes hashes exposes the pepper. Instead: Key Vault, with a version id for rotation.
  • Mistake: Using bcrypt on passwords longer than 72 bytes without knowing it truncates. Why it is wrong: long passphrases lose entropy silently. Instead: pre-hash with HMAC or use Argon2id.
  • Mistake: Setting the work factor so high that login takes a second. Why it is wrong: it creates a cheap DoS vector. Instead: 50-250 ms plus rate limiting and lockout.
  • Mistake: Logging the request body on the login endpoint. Why it is wrong: plaintext passwords end up in Application Insights. Instead: exclude credential fields from request logging.

🏛 Senior insight: trade-offs

The strongest move is often not to store passwords at all: delegate to Entra ID or Entra External ID, or go passwordless with passkeys. When you must own them, Identity's defaults are good enough for most systems, and your effort is better spent on rate limiting, MFA and breached-password checks than on swapping PBKDF2 for Argon2id.

Option When it fits Cost When not
Identity PasswordHasher (PBKDF2) Most ASP.NET Core apps, FIPS needs Zero code When policy mandates memory-hard hashing
Custom Argon2id IPasswordHasher High-value targets, security-led orgs A vetted dependency, memory per login Tight memory budgets under login bursts
External IdP / passkeys Customer and workforce identity at scale Licence, integration Offline or air-gapped systems

Measure it: hash time per instance, login CPU during a spike, and the share of hashes still on old formats (a simple query on the format prefix) as a migration metric.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions using ASP.NET Core Identity for password hashing. Why: Checks breadth: what Identity gives beyond hashing and when an external IdP is the better choice.
    How to answer

    ASP.NET Core Identity is a membership library: user and role stores (usually EF Core), password hashing with PasswordHasher (PBKDF2 with HMAC-SHA512 and 100,000 iterations), lockout after failed attempts, email confirmation, password reset tokens, two-factor with authenticator apps and recovery codes, the security stamp, and since .NET 10 passkeys. MapIdentityApi adds ready-made register, login and refresh endpoints for SPAs and mobile apps.

    Use it when one app owns its own users. Choose an external identity provider (Microsoft Entra ID for staff, Entra External ID, Auth0 or similar for customers) when you need single sign-on across apps, federation with other organisations, conditional access, or you don't want to own password security and compliance yourself.

    The trade-off: Identity is free and fully in your control, but every security feature and incident is yours to run.

  2. When: Candidate says hashing alone doesn't stop credential stuffing. Why: Checks knowledge of MFA methods, passkeys and phishing resistance.
    How to answer

    MFA methods differ mainly in phishing resistance.

    • SMS codes are vulnerable to SIM swap and interception. TOTP apps (RFC 6238) are better, but a fake login page can relay the code in real time. Push approvals suffer from MFA fatigue unless number matching is used.
    • WebAuthn/FIDO2 passkeys use a key pair per site: the private key never leaves the authenticator and the browser binds every signature to the relying party ID (the real domain), so a look-alike site gets nothing usable.

    ASP.NET Core Identity in .NET 10 supports passkey registration and sign-in (MakePasskeyCreationOptionsAsync, PerformPasskeyAttestationAsync, PasskeySignInAsync). The ACSC Essential Eight has required phishing-resistant MFA from Maturity Level 2 since its November 2023 update.

    The trade-off: passkeys are the strongest and easiest for users, but account recovery and device loss need careful design.

🛠 Real-world problems: how you handle them

Legacy SHA-1 password table found during a pen test
Situation
A [customer portal with about 300,000 accounts] migrated from ASP.NET Membership still stored unsalted SHA-1 hashes. The pen testers obtained a database backup from [a misconfigured storage account] and cracked a large share offline.
Signals
Pen test report finding rated Critical; [40%] of a 10,000-row sample cracked in [under 12 hours] on one GPU; many users shared identical hashes.
Investigation
Queried hash formats with `SELECT LEFT(PasswordHash, 13), COUNT(*) ... GROUP BY`; checked Application Insights for credential-stuffing patterns on /login; reviewed who had access to the backup container with Azure Activity Log; assessed whether the backup exposure was an eligible data breach under the NDB scheme with the privacy officer.
Resolution
Immediately revoked the storage SAS and made the container private. Same day, a migration wrapped every SHA-1 hash in PBKDF2-HMAC-SHA512 (210,000 iterations, per-row salt). Deployed `LegacyAwarePasswordHasher` so logins rehash to Identity V3. After 60 days, forced resets for the rest.
Prevention
Login rate limiting and lockout; a dashboard of the share of hashes per format; an architecture test that fails if `SHA1` or `MD5` is used outside the migration hasher; storage accounts with public access disabled by Azure Policy.

How to tell it (STAR)

**S:** At [company] a pen test found our [customer portal] still stored unsalted SHA-1 password hashes, and a backup was reachable from [a public storage container]. **T:** I owned closing the finding without forcing [300,000] users through a reset in one go. **A:** I locked down the storage within the hour, then wrote a migration that wrapped every legacy hash in PBKDF2 so nothing weak stayed at rest, and a custom `IPasswordHasher` that verified the wrapped format and returned `SuccessRehashNeeded` so Identity upgraded users as they signed in. I worked with [the privacy officer] on the NDB assessment and added login rate limiting. **R:** The retest cracked [0] hashes, [about 70%] of active users were on native hashes within [60 days], and the rest went through a targeted reset with [under 2%] support contacts.

More in Cryptography

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me