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

📚 Interview question

How do you manage and rotate encryption keys in an Azure-hosted .NET system? Explain Key Vault keys versus secrets, envelope encryption with data keys and key-encryption keys, how to rotate a key without downtime using key ids, and when you would need an HSM or Managed HSM.

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.

Senior Theory Advanced azure-key-vault cryptography envelope-encryption key-management key-rotation security

🎯 Key points

  • Key Vault keys are used through operations (wrap, unwrap, sign) and are non-exportable unless created as exportable with a release policy (secure key release, HSM tiers); secrets are values your app downloads
  • Envelope encryption: local AES DEK per record set, wrapped by a KEK in Key Vault; only the wrapped DEK is stored
  • Each ciphertext stores the versioned key id, so decrypt targets the exact key version that wrapped it while new data uses the latest
  • Rotation: new version, write with it, keep old versions enabled for decrypt, rewrap DEKs in the background, disable only when logs show zero use
  • Software-protected (Standard) vs HSM-protected (Premium, FIPS 140-3 Level 3) vs single-tenant Managed HSM for custody and BYOK
  • Least privilege with Azure RBAC, managed identity, soft delete and purge protection; AuditEvent logs to Log Analytics with alerts on unusual use
  • Availability and DR: Key Vault replicates to the paired region (read-only during failover, Australia East pairs with Southeast); cache DEKs and plan for vault outage
  • Cache unwrapped DEKs briefly to stay under Key Vault throttling limits

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 CryptographyClient and 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."


Keys vs secrets vs certificates

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

Rotation options

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

Key Vault tiers

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

Production example

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.

🔍 What the interviewer is checking

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

  • Distinguishes keys from secrets and explains envelope encryption
  • Stores versioned key ids and describes zero-downtime rotation with evidence (logs) before disabling versions
  • Mentions purge protection, RBAC least privilege, audit logging, throttling and regional failover
  • Can say when customer-managed keys or HSMs are required (APRA CPS 234, PCI DSS, contractual key custody, crypto-shredding) and when they're not
  • Describes a rotation or audit they actually ran, with the runbook

Red flags

  • Keys in appsettings.json or downloaded secrets for data encryption
  • "Rotate" means delete and replace
  • No awareness of throttling, availability or who can delete a key

📚 Learn in depth

1. Envelope encryption

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.

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

3. Rotation mechanics in Key Vault

  • A rotation policy (lifetimeActions) can rotate automatically, e.g. 30 days before expiry, and notify via Event Grid (KeyNearExpiry).
  • Versions are immutable; the unversioned URI resolves to the latest.
  • Always store the versioned key id with the ciphertext, and call wrap with the latest.
  • Signing keys: publish the new public key in the JWKS before using it, keep the old until all tokens signed with it expire.

4. Access control and audit

  • Use the Azure RBAC permission model: Key Vault Crypto Service Encryption User (wrap/unwrap) for the app's managed identity, Key Vault Crypto Officer for admins via PIM.
  • Enable soft delete and purge protection; deleting a KEK otherwise destroys data.
  • Send AuditEvent logs to Log Analytics and alert on unusual unwrap volume or access from new identities.
  • Private endpoints and firewall rules; Australia East / Southeast for data residency.

5. Throttling and availability

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.

Try it yourself

  1. Create a key, wrap a random 32-byte DEK with CryptographyClient.WrapKeyAsync, then unwrap it.
  2. Rotate the key and confirm unwrap with the old versioned id still works.
  3. Set a rotation policy with a 90-day expiry and subscribe to KeyNearExpiry with Event Grid.
  4. Query Key Vault logs in Log Analytics for UnwrapKey operations by caller identity.
  5. Load-test unwraps with and without a cache and watch for 429 responses.

💻 Code

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" }
}

⚠ Common mistakes

  • Mistake: Storing an AES key as a Key Vault secret and downloading it. Why it is wrong: the key lives in app memory, dumps and possibly logs; no usage audit. Instead: a Key Vault key with wrap/unwrap (envelope encryption).
  • Mistake: Storing the unversioned key URI with ciphertext. Why it is wrong: after rotation, unwrap uses the wrong version and fails. Instead: store the versioned key id.
  • Mistake: Deleting or disabling the old version as soon as the new one exists. Why it is wrong: existing data and backups become unreadable. Instead: rewrap, verify zero usage via logs, then disable.
  • Mistake: Calling Key Vault per field per request. Why it is wrong: latency and HTTP 429 throttling. Instead: cache unwrapped DEKs briefly in memory.
  • Mistake: Purge protection off. Why it is wrong: an accidental or malicious purge destroys the KEK and all data with it. Instead: soft delete and purge protection on every vault holding KEKs.
  • Mistake: Giving the app 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.
  • Mistake: No plan for Key Vault being unavailable. Why it is wrong: every decrypt fails. Instead: caching, retries, and knowing the vault's regional failover behaviour.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate talks about loading secrets from Key Vault into configuration. Why: Checks Key Vault and App Configuration integration, refresh and rotation of secrets.
    How to answer

    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.

  2. When: Candidate describes encrypting data locally with AES-GCM. Why: Checks nonce handling and the stored payload format.
    How to answer

    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.

  3. When: Candidate mentions RSA-OAEP key wrapping. Why: Checks understanding of asymmetric padding and hybrid encryption.
    How to answer

    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.

🛠 Real-world problems: how you handle them

Key Vault throttling after moving field encryption to customer-managed keys
Situation
A [health records API] serving [about 1,200 requests per second] in Australia East moved field encryption from an AES key in appsettings to Key Vault, calling `UnwrapKey` on every read.
Signals
p95 latency rose from [80 ms to 900 ms]; Key Vault returned HTTP 429; Application Insights showed thousands of dependency calls to vault.azure.net per minute; some reads failed after retries.
Investigation
Application Insights dependency map and Key Vault metrics (`ServiceApiHit`, `ServiceApiResult` by status code); Log Analytics query on `AzureDiagnostics` for `UnwrapKey` counts by caller; code review of the decrypt path.
Resolution
Immediately added an in-memory DEK cache with a 5-minute expiry, cutting vault calls by [over 99%]. Then moved to one DEK per patient record set rather than per field and wrapped with a versioned KEK id.
Prevention
Load tests that include Key Vault calls; alerts on 429s and unwrap rate per vault; an ADR documenting the envelope encryption design, cache lifetime and rotation procedure.

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.

↩ Usually asked after

More in Cryptography

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me