skip to content

In ASP.NET Core, what breaks when the Data Protection key ring is lost or must be revoked after a leak, and what can you still recover?

level: seniorimportance: should knowfreq 30%

answer

  1. browser state heals, stored payloads do not
  2. key not found in the key ring
  3. losing the key-encryption certificate counts too
  4. IKeyManager.RevokeAllKeys(DateTimeOffset, reason)
  5. IPersistedDataProtector.DangerousUnprotect

basics

~20 s

Lost keys sign everyone out, fail pending antiforgery tokens and empty TempData, and make anything your app stored with Protect permanently unreadable. After a leak, RevokeAllKeys forces new keys; trusted stored data can be re-protected via DangerousUnprotect.

solid answer

~50 s

Everything Data Protection produced depends on the key ring. If it is lost (storage wiped, Redis key evicted, or the certificate from `ProtectKeysWithCertificate` gone, which leaves the key XML unreadable), auth cookies fail with "Unprotect ticket failed" and users become anonymous, open forms fail antiforgery validation, TempData and session cookies are ignored, and any payload you persisted with `Protect` throws `CryptographicException` ("The key {id} was not found in the key ring") forever. Browser state heals by signing in again; stored payloads do not. If the keys leaked, an attacker can forge auth cookies, so call `IKeyManager.RevokeAllKeys(DateTimeOffset.UtcNow, reason)`: unless automatic key generation is disabled, a new key is generated, and every payload under the revoked keys is rejected, which logs everyone out on purpose. Data you trust, such as rows in your own database, can still be read with `IPersistedDataProtector.DangerousUnprotect(..., ignoreRevocationErrors: true, ...)` and protected again with the new key.

code

csharp · 20 lines
csharp
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.DataProtection.KeyManagement;

// One-off admin task after the key store was exposed
var keyManager = app.Services.GetRequiredService<IKeyManager>();
keyManager.RevokeAllKeys(DateTimeOffset.UtcNow, reason: "Key store exposed");

// Move trusted stored payloads to the new key
IDataProtector protector = app.Services.GetDataProtector("TravelSite.PartnerTokens.v1");
if (protector is IPersistedDataProtector persisted)
{
    foreach (var row in db.PartnerTokens)
    {
        byte[] plain = persisted.DangerousUnprotect(row.Protected,
            ignoreRevocationErrors: true, out bool requiresMigration, out bool wasRevoked);
        if (requiresMigration || wasRevoked)
            row.Protected = protector.Protect(plain);
    }
    db.SaveChanges();
}

go deeper

for a junior

Know that losing the keys signs everyone out and that data your code protected and stored becomes unreadable.

for a middle

List each consumer's failure mode, the CryptographicException messages, and why browser state heals but stored payloads do not.

for a senior

Run the incident: RevokeAllKeys, restart every instance, replace the certificate, and migrate only trusted stored payloads with DangerousUnprotect.

for a principal

Decide which data may ever be stored under Data Protection and fund backups, access control and a rehearsed revocation runbook for the key store.

## What depends on the key ring Every payload Data Protection creates carries the id of the key that protected it, and `Unprotect` needs that key. When the ring is gone, each consumer fails in its own way: | Consumer | What happens without the key | |---|---| | Cookie authentication | the handler logs "Unprotect ticket failed" and treats the request as anonymous; users sign in again | | Antiforgery | "The antiforgery token could not be decrypted."; the form post is rejected with 400 Bad Request | | Cookie TempData provider | the TempData cookie is unreadable, so the message is lost | | Session middleware | the session cookie is unreadable and the user starts a new, empty session | | Your own `Protect` output stored in a database | `Unprotect` throws `CryptographicException`: "The key {id} was not found in the key ring." | The first four live in the browser and **heal themselves** the next time the user signs in or reloads a form. The last one does not: there is no master key and no backdoor, so a payload whose key is gone is gone. ## Ways to lose a key ring - The repository is deleted or was never persistent (a container's own folder, an in-memory fallback). - Redis used for `PersistKeysToStackExchangeRedis` evicts or loses the key ring entry. - The certificate used by `ProtectKeysWithCertificate` is lost or its private key is unavailable: the key XML is still there but cannot be decrypted, which is the same outcome. - Someone calls `IDeletableKeyManager.DeleteKeys` on keys that still protect live data. The defence is boring: back up the key store **and** the certificate, restrict who can write to them, and never make a Data Protection payload the only copy of data you must keep. ## Responding to a leak If the key XML (and its key-encryption certificate) leaked, an attacker can create valid auth cookies for any user. Rotating forward is not enough, because old keys still unprotect. Revoke them: 1. Resolve `IKeyManager` and call **`RevokeAllKeys(DateTimeOffset.UtcNow, "reason")`**. It writes a revocation element to the repository that revokes every key created strictly before that moment. `RevokeKey(Guid, reason)` revokes a single key. 2. With the default key revoked, the system generates a new key with **immediate** activation, unless automatic key generation is disabled. 3. `Unprotect` now throws `CryptographicException` ("The key ... has been revoked") for anything protected before. Everyone is signed out, which is the point. 4. Other instances notice at their next key ring refresh (about every 24 hours), so restart or redeploy every instance right after revoking. 5. Replace the certificate. For a routine rotation without a leak, call `ProtectKeysWithCertificate(newCert)` and `UnprotectKeysWithAnyCertificate(oldCert)` so existing key XML stays readable; after a leak, retire the old certificate once the old keys are revoked. ## Recovering data you trust Revocation does not destroy keys, so stored payloads can still be read deliberately. Cast a protector to **`IPersistedDataProtector`** (use `as`; not every protector supports it) and call `DangerousUnprotect(bytes, ignoreRevocationErrors: true, out bool requiresMigration, out bool wasRevoked)`. When `requiresMigration` or `wasRevoked` is true, protect the plaintext again with the normal `Protect` so it moves to the new key. Only do this for data from a trusted source, such as your own database. A revoked key may be in an attacker's hands, so anything a **client** sends under that key must stay rejected. Deleted keys, unlike revoked ones, cannot be recovered at all. ## Rehearse it before you need it 1. Restore the key store and certificate from backup into a staging environment and confirm that cookies and stored payloads from production-like data still unprotect. 2. Run `RevokeAllKeys` there and confirm that sign-ins fail as expected and that the migration job moves stored rows to the new key. 3. Write down who may revoke keys and how every instance gets restarted afterwards.

  • How do you rotate the certificate used by ProtectKeysWithCertificate without making existing keys unreadable?
    Point `ProtectKeysWithCertificate` at the new certificate so new keys are encrypted with it, and add `UnprotectKeysWithAnyCertificate(oldCert)` so key XML encrypted with the old certificate can still be decrypted. Keep the old certificate available on every instance until all keys it protects have expired and you no longer need their payloads.
  • Why is revoking all keys better than deleting them after a leak?
    Revocation makes `Unprotect` reject every payload under those keys, which stops forged cookies, while keeping the keys so trusted stored data can still be recovered with `DangerousUnprotect`. Deleting through `IDeletableKeyManager.DeleteKeys` also stops forgeries but leaves no way to recover data that only existed in protected form.

  • Lost Data Protection keys can be regenerated from the application name.
  • After keys are lost, every request fails with a 500 until they are restored.
  • Rolling to a new default key is enough to invalidate cookies forged with a leaked key.
  • DangerousUnprotect is safe to use on payloads sent by clients.
  • Keeping the key XML backed up is enough even if the encryption certificate is lost.