The Analogy: The Master Key and the Signature Book
Behind a hotel's front desk there are two things locked away, and confusing them causes most of the industry's security incidents. The first is the master keycard. Staff need to use it, which means the hotel must be able to get it back out of the drawer intact — it is a secret to be kept and used. The second is the signature book: when a guest collects a parcel they sign, and the clerk compares the new signature to the old one. The hotel never needs to reproduce a guest's signature; it only ever needs to compare one. That distinction is the whole topic. Connection strings and API keys are master keycards — you protect them, you rotate them, and you must be able to read them back. Passwords are signatures — you store something that lets you check a new attempt, and you make sure the stored form cannot be turned back into the original.
Now consider where the master keycard lives. Taped to the monitor is where it ends up when nobody thought about it, and that is what a secret committed to appsettings.json amounts to: visible to everyone who walks past, and still visible in the photograph taken last year even after you peel it off. Git history is that photograph. The safe behind the desk is the equivalent of environment variables injected by the platform, a key vault, or a container secret — the key is available to the people doing the job, at the moment they do it, and never written down where it outlives its usefulness.
The signature book has a subtler design. A forger who steals the book wants to practise until their forgery passes, so a good clerk deliberately checks slowly, stroke by stroke, and every guest signs with slightly different ink so two identical signatures do not produce identical entries. Those are the two ideas behind modern password storage. The unique ink is a salt: a random value stored beside each hash so that two people with the same password get different stored values, and one precomputed table cannot crack the whole book. The slow check is the work factor: PBKDF2 iterations, bcrypt cost, Argon2 memory. A plain SHA-256 is a clerk who glances at a signature in a microsecond, which is precisely what lets an attacker with a stolen database try billions of guesses an hour.
The last part of the analogy is the most important and the least followed: the hotel does not design its own locks. Locksmithing is a specialist trade, and a hand-carved lock that "looks fine" fails against someone who picks locks for a living. In code, this means the standard library and well-reviewed packages do the cryptography — Rfc2898DeriveBytes, PasswordHasher<T>, AesGcm, bcrypt, Argon2 — and you supply parameters and plumbing. Every home-made XOR "encryption", every clever custom hash, every "we just base64 it" has the same ending.
Syntax or Core Structure
Two mechanisms, side by side: configuration that reads a secret from wherever the environment supplies it, and a password hasher that stores something safe to lose.
dotnet new console -o Vaults
cd Vaults
dotnet add package Microsoft.Extensions.Configuration
dotnet add package Microsoft.Extensions.Configuration.EnvironmentVariables
dotnet add package Microsoft.Extensions.Identity.Core
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Configuration;
// Sources are layered: the last one to supply a key wins.
IConfiguration configuration = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string?>
{
["ConnectionStrings:Shop"] = "Server=localhost;Database=shop;", // safe default
["Payments:ApiKey"] = "placeholder-not-a-key" // checked in, harmless
})
.AddInMemoryCollection(new Dictionary<string, string?>
{
["Payments:ApiKey"] = "from-the-secret-store" // stands in for a vault
})
.AddEnvironmentVariables() // Payments__ApiKey wins on a server
.Build();
string? apiKey = configuration["Payments:ApiKey"];
string? shop = configuration.GetConnectionString("Shop");
Console.WriteLine($"payments api key: {Mask(apiKey)}");
Console.WriteLine($"connection string: {shop}");
Console.WriteLine();
// Passwords: hash once, compare forever, never store the original.
PasswordHasher<string> hasher = new PasswordHasher<string>();
string first = hasher.HashPassword("ada", "correct horse battery staple");
string second = hasher.HashPassword("ada", "correct horse battery staple");
byte[] raw = Convert.FromBase64String(first);
Console.WriteLine($"two hashes equal? {first == second}");
Console.WriteLine($"format marker: {raw[0]}");
Console.WriteLine($"stored bytes: {raw.Length}");
PasswordVerificationResult right = hasher.VerifyHashedPassword("ada", first, "correct horse battery staple");
PasswordVerificationResult wrong = hasher.VerifyHashedPassword("ada", first, "correct horse battery stapl");
Console.WriteLine($"right password: {right}");
Console.WriteLine($"wrong password: {wrong}");
// Print secrets like this or not at all.
static string Mask(string? value) =>
value is null || value.Length < 8
? "(not set)"
: value.Substring(0, 4) + "****(" + value.Length + " chars)";
Output:
payments api key: from****(21 chars)
connection string: Server=localhost;Database=shop;
two hashes equal? False
format marker: 1
stored bytes: 61
right password: Success
wrong password: Failed
The configuration half shows layering: the checked-in placeholder was overridden by the later source, and on a real server AddEnvironmentVariables would override that in turn — Payments__ApiKey with a double underscore, because colons are not legal in environment variable names on every platform. Nothing in the file needs to change between a laptop and production; only the outermost layer differs.
The hashing half shows three properties worth naming. Hashing the same password twice gives different results, because each call generates a fresh random salt — so an attacker cannot tell that two users chose the same password. The stored value is 61 bytes: a one-byte format marker, twelve bytes describing the algorithm, iteration count and salt length, a 16-byte salt and a 32-byte derived key. Everything needed to verify a future attempt travels with the hash, which is what lets you change the iteration count later without invalidating existing accounts. And verification returns an enum rather than a bool, because there is a third answer: SuccessRehashNeeded means "the password was right, but this hash used weaker parameters than you now require".
Technical Depth: Where Secrets Live and How Hashes Differ
The configuration ladder
WebApplication.CreateBuilder installs these providers in order, and later providers win. Knowing the order is how you answer "why is it still using the old connection string".
| Order | Provider | Present in | Suitable for secrets |
|---|---|---|---|
| 1 | appsettings.json | source control | no |
| 2 | appsettings.{Environment}.json | source control | no |
| 3 | User Secrets | Development only, per developer | yes, on a laptop |
| 4 | Environment variables | every host | yes |
| 5 | Command line arguments | manual runs | no, they show in process lists |
| 6 | Anything you add | AddAzureKeyVault, AddSystemsManager, custom | yes |
# One-time per project: writes a UserSecretsId into the .csproj
dotnet user-secrets init
# Values land outside the repository, keyed by that id
dotnet user-secrets set "Payments:ApiKey" "sk_test_placeholder"
dotnet user-secrets list
User secrets are stored as plain JSON under your profile — %APPDATA%\Microsoft\UserSecrets\<id>\secrets.json on Windows, ~/.microsoft/usersecrets/<id>/secrets.json elsewhere. They are not encrypted. Their only virtue is living outside the repository, and they load only in the Development environment, which is exactly the right scope.
Bind and validate at startup
A missing secret should stop deployment, not surface as a NullReferenceException during the first payment.
public sealed class PaymentOptions
{
[Required, MinLength(20)]
public string ApiKey { get; set; } = "";
[Range(1, 30)]
public int TimeoutSeconds { get; set; } = 10;
}
builder.Services.AddOptions<PaymentOptions>()
.Bind(builder.Configuration.GetSection("Payments"))
.ValidateDataAnnotations()
.ValidateOnStart(); // fails the host, loudly, at boot
Encoding, encryption, hashing: three different words
| Operation | Reversible | Needs a key | Example | Correct use |
|---|---|---|---|---|
| Encoding | yes, by anyone | no | Base64, URL encoding | transport, never protection |
| Encryption | yes, with the key | yes | AesGcm, IDataProtector | data you must read back |
| Fast hash | no | no | SHA256.HashData | integrity, high-entropy tokens |
| Keyed hash | no | yes | HMACSHA256 | proving a message came from you |
| Password hash | no | no | PBKDF2, bcrypt, Argon2id | low-entropy human input |
Base64 is the one people get wrong out loud: "the password is encrypted, look at it" describes a string that anyone can decode in a browser console. And note the last two rows are both one-way — the difference is that a password hash is deliberately expensive, because the input it protects has perhaps 30 bits of entropy while a random API key has 192.
Choosing a password algorithm
| Algorithm | Available via | Cost knobs | Notes |
|---|---|---|---|
| PBKDF2-SHA256 | built in (Rfc2898DeriveBytes, PasswordHasher<T>) | iterations | fine, FIPS-friendly, weakest against GPUs |
| bcrypt | BCrypt.Net-Next | cost factor | battle-tested, 72-byte input limit |
| Argon2id | Konscious.Security.Cryptography, Isopoh.Cryptography.Argon2 | memory, iterations, parallelism | current recommendation; memory-hard |
Tune the parameters to a target time, not to a number you copied from a blog post in 2015: aim for roughly 100 to 250 ms per hash on your production hardware, measure it, and revisit yearly. The stored hash carries its own parameters, so raising the cost later is a rehash-on-next-login migration rather than a mass password reset.
Comparing secrets without leaking timing
// Wrong: returns as soon as two bytes differ, so response time reveals the prefix.
bool naive = presented == stored;
// Right: always inspects every byte.
bool safe = CryptographicOperations.FixedTimeEquals(
Convert.FromBase64String(presented),
Convert.FromBase64String(stored));
Use FixedTimeEquals for API keys, HMAC signatures, webhook secrets, password-reset tokens and anything else an attacker can submit repeatedly. Password hash verification already runs in fixed time inside the library.
Generating values nobody can guess
byte[] key = RandomNumberGenerator.GetBytes(32); // 256 bits, cryptographic
string token = Convert.ToBase64String(key).TrimEnd('=');
string code = RandomNumberGenerator.GetString("0123456789", 8); // .NET 8+, unbiased
Random is a statistical generator: fast, repeatable from a seed, and predictable from a handful of outputs. Guid.NewGuid() is not a security primitive either — version 4 GUIDs carry 122 random bits on .NET, but the type advertises uniqueness, not unpredictability, and reviewers cannot tell at a glance which guarantee you were relying on. For anything that acts as a credential, say RandomNumberGenerator so the intent is unambiguous.
Reversible protection you did not write yourself
When you genuinely need to read a value back — an encrypted cookie payload, a signed unsubscribe link, a short-lived reference — use ASP.NET Core Data Protection rather than AesGcm directly:
IDataProtector protector = provider.CreateProtector("Unsubscribe.v1");
string wrapped = protector.Protect(emailAddress);
string original = protector.Unprotect(wrapped); // throws if tampered with
It handles key derivation, authenticated encryption, and key rotation. The one thing it needs from you is a persisted key ring — PersistKeysToFileSystem on a shared volume, or PersistKeysToAzureBlobStorage — because the default in-memory keys mean every restart invalidates every cookie, and every instance in a farm disagrees with its neighbours.
Hygiene that catches the rest
| Risk | Control |
|---|---|
| Secret committed by accident | .gitignore for .env and *.secrets.json, plus push protection or a scanning hook |
| Secret in logs | never log raw configuration, headers, or GetDebugView() output |
| Secret in an image | build-time --secret mounts, not ENV or COPY of a .env file |
| Secret shipped to a browser | any key reaching client JavaScript is public; proxy the call instead |
| Secret with no expiry | rotation schedule, and prefer managed identity so no secret exists to leak |
If a secret does leak, the only fix is rotation. Removing the commit does not help: the value existed, it is in clones, in build logs, in a fork, in someone's terminal scrollback. Revoke it, issue a new one, and check what the old one touched.
Real World Example: Getting Off An Unsalted Hash
An older system stored passwords as a bare SHA-256 of the password — no salt, no work factor. You cannot recompute a better hash from the stored value, because that would require the original password. But there is exactly one moment when the server legitimately holds the plaintext: the instant a user signs in successfully. That is the seam a migration lives in.
The program below stores one legacy account and one modern account, then walks five sign-in attempts and issues an API key. Nothing secret is ever printed.
using System.Security.Cryptography;
using System.Text;
const int Iterations = 100_000;
Dictionary<string, Account> accounts = new Dictionary<string, Account>(StringComparer.OrdinalIgnoreCase)
{
["ada@example.com"] = new Account("ada@example.com", LegacySha256("hunter2"), "sha256"),
["grace@example.com"] = new Account("grace@example.com", HashPbkdf2("correct horse", Iterations), "pbkdf2")
};
Account ada = accounts["ada@example.com"];
Account grace = accounts["grace@example.com"];
Console.WriteLine($"seeded ada format={ada.Format} (unsalted, legacy)");
Console.WriteLine($"seeded grace format={grace.Format} iterations={Iterations}");
Console.WriteLine();
Attempt("ada@example.com", "hunter2"); // upgrades on the way through
Attempt("ada@example.com", "hunter2"); // already upgraded
Attempt("ada@example.com", "hunter3");
Attempt("nobody@example.com", "hunter2");
Attempt("grace@example.com", "correct horse");
Console.WriteLine();
// An API key is high-entropy, so a single fast hash is the right storage.
string apiKey = "sk_" + Convert.ToBase64String(RandomNumberGenerator.GetBytes(24));
string apiKeyHash = Convert.ToBase64String(SHA256.HashData(Encoding.UTF8.GetBytes(apiKey)));
bool presentedOk = CheckKey(apiKey, apiKeyHash);
bool tamperedOk = CheckKey(apiKey + "x", apiKeyHash);
Console.WriteLine($"issued api key {Mask(apiKey)} shown once, stored as sha256");
Console.WriteLine($"presented key ok {presentedOk}");
Console.WriteLine($"tampered key ok {tamperedOk}");
void Attempt(string email, string password)
{
(bool ok, string note) = Login(email, password);
Console.WriteLine($"login {email,-18} -> {ok,-5} {note}");
}
(bool Ok, string Note) Login(string email, string password)
{
if (!accounts.TryGetValue(email, out Account? account))
{
// Do the work anyway: a missing account must not answer faster than a wrong password.
HashPbkdf2(password, Iterations);
return (false, "rejected");
}
bool verified = account.Format switch
{
"pbkdf2" => VerifyPbkdf2(password, account.Hash),
"sha256" => VerifySha256(password, account.Hash),
_ => false
};
if (!verified)
{
return (false, "rejected");
}
if (account.Format != "pbkdf2")
{
// The one moment the plaintext is legitimately in hand.
accounts[email] = account with { Hash = HashPbkdf2(password, Iterations), Format = "pbkdf2" };
return (true, "signed in, hash upgraded to pbkdf2");
}
return (true, "signed in");
}
static string HashPbkdf2(string password, int iterations)
{
byte[] salt = RandomNumberGenerator.GetBytes(16);
byte[] subkey = Rfc2898DeriveBytes.Pbkdf2(password, salt, iterations, HashAlgorithmName.SHA256, 32);
return "pbkdf2:" + iterations + ":" + Convert.ToBase64String(salt) + ":" + Convert.ToBase64String(subkey);
}
static bool VerifyPbkdf2(string password, string stored)
{
string[] parts = stored.Split(':');
int iterations = int.Parse(parts[1]);
byte[] salt = Convert.FromBase64String(parts[2]);
byte[] expected = Convert.FromBase64String(parts[3]);
byte[] actual = Rfc2898DeriveBytes.Pbkdf2(password, salt, iterations, HashAlgorithmName.SHA256, expected.Length);
return CryptographicOperations.FixedTimeEquals(expected, actual);
}
static string LegacySha256(string password) =>
"sha256:" + Convert.ToBase64String(SHA256.HashData(Encoding.UTF8.GetBytes(password)));
static bool VerifySha256(string password, string stored)
{
byte[] expected = Convert.FromBase64String(stored.Split(':')[1]);
byte[] actual = SHA256.HashData(Encoding.UTF8.GetBytes(password));
return CryptographicOperations.FixedTimeEquals(expected, actual);
}
static bool CheckKey(string presented, string storedHash)
{
byte[] expected = Convert.FromBase64String(storedHash);
byte[] actual = SHA256.HashData(Encoding.UTF8.GetBytes(presented));
return CryptographicOperations.FixedTimeEquals(expected, actual);
}
static string Mask(string value) => value.Substring(0, 3) + "****(" + value.Length + " chars)";
sealed record Account(string Email, string Hash, string Format);
Output:
seeded ada format=sha256 (unsalted, legacy)
seeded grace format=pbkdf2 iterations=100000
login ada@example.com -> True signed in, hash upgraded to pbkdf2
login ada@example.com -> True signed in
login ada@example.com -> False rejected
login nobody@example.com -> False rejected
login grace@example.com -> True signed in
issued api key sk_****(35 chars) shown once, stored as sha256
presented key ok True
tampered key ok False
The first two login lines are the migration. Ada's stored value was an unsalted SHA-256; her first successful sign-in verified against the old format and immediately replaced the record with a salted PBKDF2 hash, which is why the second identical attempt reports plain signed in. No user was emailed, no password was reset, and after a few weeks the remaining sha256 rows belong to accounts nobody uses — at which point you can disable that verifier and force a reset for the stragglers. The rule that makes this work is that verification is chosen by the format recorded with each row, never by a global setting.
The third and fourth lines are deliberately identical. A wrong password and an unknown email produce the same word, rejected, because "no such account" is an answer worth money to whoever is testing a list of leaked addresses against your site. The HashPbkdf2 call on the missing-account path exists for the same reason: without it, unknown emails would return in microseconds while real ones take a hundred milliseconds, and the timing alone would rebuild the answer you refused to print. This is mitigation rather than proof — a determined attacker can still find signals in other places, such as which addresses the signup form refuses — but it removes the easy one.
The API key at the bottom uses a completely different recipe on purpose, and the contrast is the point of the lesson. hunter2 is a human choice with maybe thirty bits of entropy, so PBKDF2 spends a hundred thousand iterations making each guess expensive. The key is twenty-four bytes from a cryptographic generator — 192 bits — so guessing it is hopeless no matter how fast the hash runs, and a single SHA-256 is both sufficient and cheap enough to run on every request. "Always use bcrypt" is good advice for passwords and wasted effort for random tokens; what decides is the entropy of the input.
Notice what the server keeps. It stores a hash of the key, not the key, which is why the key is printed once and never again — the same "we cannot recover it, only replace it" property that passwords have. Every comparison goes through FixedTimeEquals, so an attacker cannot narrow a key down byte by byte from response times. And every line of output is a boolean, a length, or a format name: the transcript of this program could be pasted into a public bug report without burning anything.
Common Mistakes
- Committing the real value into
appsettings.json. It is now in every clone and every fork of the history. Deleting the line later changes nothing; the credential must be rotated. - Believing user secrets are encrypted.
dotnet user-secretswrites plain JSON into your profile. It keeps secrets out of the repository, and that is all it does. - Using SHA-256 or MD5 for passwords. Fast is the wrong property. A modern GPU tries billions of SHA-256 guesses per second against a stolen table.
- One global salt, or no salt. A shared salt means identical passwords produce identical hashes, so cracking one row cracks every account that reused that password.
- Encrypting passwords instead of hashing them. Encryption implies a key that can decrypt, and that key will be on the same server as the database. You never need the original password.
- Comparing secrets with
==. String comparison short-circuits on the first difference, which turns "guess the whole key" into "guess one byte at a time". UseCryptographicOperations.FixedTimeEquals.
- Generating credentials with
RandomorGuid.NewGuid(). Password reset tokens produced this way have been guessed in the wild.RandomNumberGeneratorcosts nothing extra and states the intent. - Logging the thing you were protecting.
GetDebugView(), a dumpedAuthorizationheader, a serialised options object in an error report, or a.envfile copied into a Docker image all publish the secret to whoever reads logs. - Shipping a key to the client. A key embedded in JavaScript, a mobile binary or a desktop app is public the moment it ships. Proxy the call through your own server instead.
- Mangling passwords before hashing. Truncating to sixteen characters, stripping spaces or upper-casing throws away entropy and breaks password managers, and the limits are always invisible to the user until login fails.
Best Practices
- Layer configuration so the same build runs everywhere: harmless defaults in
appsettings.json, user secrets on a laptop, environment variables or a vault in production, and never a real value in the repository. - Bind secrets to an options class with
ValidateDataAnnotations().ValidateOnStart(), so a missing or malformed key fails the deployment instead of the first customer request. - Prefer having no secret at all: managed identity, workload identity federation and IAM roles let the platform vouch for your process, and there is nothing to leak or rotate.
- Use a real password hasher —
PasswordHasher<T>, bcrypt or Argon2id — store its parameters inside the hash, and rehash on successful login when you raise the cost. - Make credentials at least 128 bits from
RandomNumberGenerator, store only their hash, show them once, and give them a recognisable prefix such assk_so secret scanners can spot a leak. - Route every secret comparison through
CryptographicOperations.FixedTimeEquals, and route every reversible protection throughIDataProtectororAesGcmrather than a construction of your own. - Mask before you print: log key names, lengths and prefixes, never values, and treat any secret that has appeared in a log, a CI transcript or a screenshot as already compromised.
- Plan rotation before you need it — short-lived credentials, a documented revoke-and-reissue procedure, and secret scanning on the repository so you find out from a bot rather than from an invoice.
Practice Exercises
- Move the API key out of the syntax example's code entirely: add
appsettings.jsonwith an empty placeholder, set a real-looking value withdotnet user-secrets, then override it with aPayments__ApiKeyenvironment variable. Print only the mask and prove from the output which layer won each time. - Add a work-factor upgrade to the real world example. Raise
Iterationsto 210000, teachLoginto rehash when the stored iteration count is lower than the current one, and show from the transcript that grace's hash upgrades on her next sign-in and stays put on the one after. - Add a
PaymentOptionsclass with[Required]and[MinLength(20)], wire it up withValidateOnStart, and confirm the host refuses to start when the key is missing. Then write down which exception type you saw and where the message appeared. - Implement single-use password reset tokens: 32 random bytes shown once, only a SHA-256 hash plus a 15 minute expiry stored, constant-time comparison on redemption, and the token deleted after use. Produce output covering four cases — valid, wrong token, expired, and reused.