Covers key management for .NET on Azure: Key Vault keys vs secrets vs certificates, envelope encryption (DEK/KEK), key versioning and zero-downtime rotation, re-encryption strategies, HSM tiers, access control and auditing.
Treat keys as long-lived identities with a lifecycle. In Azure Key Vault, a key is non-exportable: you send data to it for wrap/unwrap/sign, while a secret is a value your app downloads (connection strings, API keys). For data encryption use envelope encryption: generate a random data encryption key (DEK) locally, encrypt with AES-GCM, and have a Key Vault key-encryption key (KEK) wrap the DEK; store only the wrapped DEK beside the data.
Rotation without downtime depends on key ids: every ciphertext records which key version wrapped it, new writes use the newest version, old versions stay enabled for decrypt, and a background job optionally rewraps DEKs before old versions are disabled. Use Premium (HSM-backed) or Managed HSM when regulation or key value demands it. The trade-off is security and auditability versus latency, throttling and operational complexity.
"I start by separating the three things Key Vault stores. Secrets are values the app reads, like a third-party API key. Certificates are X.509 plus their key and renewal policy. Keys are RSA or EC keys that never leave the vault: I call wrap, unwrap or sign through
CryptographyClientand the private material stays in Key Vault's HSM-backed or software boundary. For encrypting application data I use keys, not secrets, because a downloaded AES secret lives in process memory, dumps and logs.The pattern is envelope encryption. Calling Key Vault for every field would be slow and throttled, so the app generates a random 256-bit data key, encrypts locally with AES-GCM, asks Key Vault to wrap the data key with an RSA-OAEP-256 key-encryption key, and stores the wrapped key and the KEK version with the data. Decrypt is one unwrap call, and I cache unwrapped data keys in memory for a few minutes.
Rotation is then mostly bookkeeping. For example, at [company] we had [a document store with about 20 million files] and a policy of [annual KEK rotation]. Key Vault's rotation policy created a new version; the app always wrapped new data keys with the latest version, and because every record carried the KEK version, unwrapping old ones kept working. A background job rewrapped the small data keys, not the files, so it finished in [hours, not weeks]. Only when telemetry showed zero unwraps on the old version did we disable it. [No downtime and no re-encryption of the files themselves.]
The mistake I see is 'rotation' that is really replacement: a new key, the old one deleted, and suddenly backups can't be decrypted. My senior line is: you can't rotate what you can't identify, so a key id goes in every ciphertext from day one."
| Object | What the app gets | Typical use | Rotation |
|---|---|---|---|
| Key | Results of operations only | Wrap DEKs, sign tokens | New version; old versions kept for decrypt/verify |
| Secret | The value | Connection strings, third-party API keys | New version + app reload; dual secrets on the provider side |
| Certificate | Cert, and key if exportable | TLS, mTLS, signing | Auto-renew via issuer policy |
| Strategy | How | Cost | When |
|---|---|---|---|
| Lazy | New writes use new key; old data decrypts with old version | Cheap | Default |
| Rewrap DEKs | Unwrap with old KEK, wrap with new | Small, fast | Retire a KEK version |
| Full re-encryption | Decrypt and encrypt data with new DEK | Expensive | DEK suspected compromised |
| Emergency | Disable old version immediately | Old data unreadable until rewrapped | Confirmed KEK compromise |
| Tier | Protection | When |
|---|---|---|
| Standard | Software-protected keys | Most workloads |
| Premium | HSM-backed keys (FIPS 140-3 Level 3 validated HSMs) | Regulated data, PCI DSS |
| Managed HSM | Single-tenant HSM pool, customer controls the security domain | Banks, government, strict key custody, BYOK |
With envelope encryption and a 5-minute DEK cache, our [claims API] made [about 40] Key Vault calls a minute at [1,500] requests per second, far below throttling limits; without the cache it would have been [about 90,000] a minute and throttled with HTTP 429.
Checks whether the candidate can design key management that survives rotation, outages and audits, and has practical experience running it, rather than just calling an encryption API.
Green flags
Red flags
Write: DEK = random(32)
ct = AES-GCM(DEK, data)
wDEK = KeyVault.WrapKey(KEK v7, RSA-OAEP-256, DEK)
store { kekId: "https://vault/keys/docs/v7", wDEK, nonce, ct, tag }
Read: DEK = KeyVault.UnwrapKey(kekId, wDEK) (cache for minutes)
data = AES-GCM-Decrypt(DEK, ...)
The KEK never leaves Key Vault; DEKs are small, so rotating the KEK means rewrapping kilobytes, not re-encrypting terabytes. Azure Storage, Azure SQL TDE with customer-managed keys and Always Encrypted all use this hierarchy.
HSM root (Microsoft or your security domain)
-> KEK in Key Vault (versions v1..vN)
-> DEK per tenant / file / day
-> data
Granularity is a trade-off: a DEK per record limits blast radius but costs unwrap calls; per tenant enables crypto-shredding (delete the DEK and the tenant's data is unreadable, useful for right-to-erasure requests).
lifetimeActions) can rotate automatically, e.g. 30 days before expiry, and notify via Event Grid (KeyNearExpiry).Key Vault Crypto Service Encryption User (wrap/unwrap) for the app's managed identity, Key Vault Crypto Officer for admins via PIM.AuditEvent logs to Log Analytics and alert on unusual unwrap volume or access from new identities.Key Vault has per-vault transaction limits (per 10-second windows, lower for RSA HSM operations). Cache DEKs, use EC or AES operations where possible, and handle 429 with retries. Key Vault is a dependency for decryption: if it's unavailable and nothing is cached, reads fail, so design for that.
CryptographyClient.WrapKeyAsync, then unwrap it.KeyNearExpiry with Event Grid.UnwrapKey operations by caller identity.Envelope encryption with Azure Key Vault (Azure.Security.KeyVault.Keys), versioned KEK ids and a short-lived DEK cache.
using System.Security.Cryptography;
using Azure.Core;
using Azure.Security.KeyVault.Keys;
using Azure.Security.KeyVault.Keys.Cryptography;
using Microsoft.Extensions.Caching.Memory;
namespace Documents.Crypto;
public sealed record EncryptedBlob(string KekId, byte[] WrappedDek, byte[] Nonce, byte[] Ciphertext, byte[] Tag);
public sealed class EnvelopeEncryptor(KeyClient keys, TokenCredential credential, IMemoryCache cache)
{
private const string KekName = "documents-kek";
public async Task<EncryptedBlob> EncryptAsync(byte[] plaintext, CancellationToken ct)
{
KeyVaultKey kek = await keys.GetKeyAsync(KekName, cancellationToken: ct); // latest version
var crypto = new CryptographyClient(kek.Id, credential);
byte[] dek = RandomNumberGenerator.GetBytes(32);
byte[] nonce = RandomNumberGenerator.GetBytes(12);
byte[] cipher = new byte[plaintext.Length], tag = new byte[16];
using (var aes = new AesGcm(dek, 16)) aes.Encrypt(nonce, plaintext, cipher, tag);
WrapResult wrapped = await crypto.WrapKeyAsync(KeyWrapAlgorithm.RsaOaep256, dek, ct);
CryptographicOperations.ZeroMemory(dek);
// Store the VERSIONED key id: rotation later depends on it.
return new EncryptedBlob(wrapped.KeyId, wrapped.EncryptedKey, nonce, cipher, tag);
}
public async Task<byte[]> DecryptAsync(EncryptedBlob blob, CancellationToken ct)
{
string cacheKey = $"dek:{blob.KekId}:{Convert.ToBase64String(blob.WrappedDek)}";
byte[] dek = (await cache.GetOrCreateAsync(cacheKey, async entry =>
{
entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5); // stay under throttling limits
var crypto = new CryptographyClient(new Uri(blob.KekId), credential);
UnwrapResult r = await crypto.UnwrapKeyAsync(KeyWrapAlgorithm.RsaOaep256, blob.WrappedDek, ct);
return r.Key;
}))!;
byte[] plain = new byte[blob.Ciphertext.Length];
using var aes = new AesGcm(dek, 16);
aes.Decrypt(blob.Nonce, blob.Ciphertext, blob.Tag, plain);
return plain;
}
}
// Key rotation policy (az keyvault key rotation-policy update --value policy.json)
{
"lifetimeActions": [
{ "trigger": { "timeBeforeExpiry": "P30D" }, "action": { "type": "Rotate" } },
{ "trigger": { "timeBeforeExpiry": "P45D" }, "action": { "type": "Notify" } }
],
"attributes": { "expiryTime": "P1Y" }
}
Key Vault Administrator or access policies with all permissions. Why it is wrong: a compromised app can delete or export material. Instead: Crypto Service Encryption User scoped to the key.Key management is mostly governance: who can use a key, who can rotate or delete it, how you prove that, and how you recover. Microsoft-managed keys are fine for most data (Azure encrypts storage and SQL at rest by default); customer-managed keys add control and revocation ability but also the ability to lock yourself out. Choose CMK when a regulator, contract or customer demands key custody, not by default.
| Option | When it fits | Cost | When not |
|---|---|---|---|
| Platform-managed keys | Default encryption at rest | None | When you must revoke access independently of Microsoft |
| Customer-managed keys in Key Vault | Regulated data, tenant-level crypto-shredding | Rotation, availability dependency | Teams without key-management maturity |
| Envelope encryption in app | Field or file encryption beyond platform encryption | Code and caching | When platform encryption meets the threat model |
| Managed HSM / BYOK | Banking, government, contractual custody | Significant cost, security domain ceremony | General SaaS |
Measure: unwrap rate and 429s per vault, the share of data on each key version (your rotation progress), and days to expiry for every key.
I'd inventory and classify every setting first: secrets, environment-specific values, shared values, and which must change live. Secrets go to Key Vault. Non-secret settings and feature flags go to Azure App Configuration with a label per environment, and secrets are referenced from there through Key Vault references. The app authenticates with its managed identity using least-privilege roles, and where possible secrets disappear entirely through passwordless Entra ID auth to SQL, Storage and Service Bus.
For refresh, use a sentinel key with a refresh interval and a secret refresh interval, and read live values through IOptionsMonitor. Rotation uses overlapping versions, so old and new both work during the window. Add start-up timeouts and replicas, and keep ValidateOnStart.
The trade-off: central, audited, rotatable configuration, in exchange for a network dependency at start-up that you must design for.
AesGcm is .NET's authenticated encryption API: AES in Galois/Counter Mode gives confidentiality and integrity in one step. You need a 256-bit key, a 12-byte nonce that is unique per encryption under that key, and you get a 16-byte tag; decryption throws AuthenticationTagMismatchException if anything was changed. Store keyId | nonce | ciphertext | tag together.
The one rule you can't break: never reuse a nonce with the same key. GCM is a stream cipher underneath, so reuse leaks the XOR of the two plaintexts and exposes the authentication key, letting an attacker forge messages. Use random nonces and rotate keys well before about 2^32 messages. Compared with AES-CBC, GCM has no padding oracle and no separate MAC to get wrong. For most app needs, ASP.NET Core Data Protection or SQL Always Encrypted wraps this for you.
Asymmetric cryptography uses a key pair: what one key does, only the other undoes. For encryption you use the recipient's public key and only their private key decrypts. For signing you use your private key and anyone verifies with your public key, proving origin and integrity.
RSA does both: use 3072-bit keys for anything new or long-lived (2048 is only the legacy floor), OAEP-SHA256 for encryption and PSS for new signature formats. ECDSA (signing) and ECDH (key agreement) on P-256/P-384 give equivalent security with much smaller keys. Asymmetric operations are slow and RSA can only encrypt a few hundred bytes, so real systems use hybrid encryption: asymmetric to agree or wrap an AES key, AES for the data, as in TLS and Key Vault key wrapping. Keep private keys non-exportable in Key Vault/HSMs, and plan for post-quantum algorithms (ML-KEM, ML-DSA in .NET 10): ASD's guidance is to move off RSA and ECC by 2030.
How to tell it (STAR)
**S:** At [company] we moved field encryption in our [health records API] to Key Vault for compliance, and latency jumped tenfold the next morning. **T:** I had to restore performance without going back to keys in config. **A:** Using Key Vault metrics and Application Insights I saw an unwrap per field per request hitting throttling limits. I added a short-lived DEK cache straight away, then redesigned to one data key per record set with versioned KEK ids so annual rotation only rewrapped small keys. I wrote the ADR and added load tests and 429 alerts. **R:** p95 dropped back to [about 85 ms], vault calls fell from [about 70,000 to under 100] a minute, and our first rotation completed with [zero] downtime.
Last updated 23 Nov 2026.