The Data Protection API (DPAPI), which is included into ASP.NET Core, offers developers easy, safe, and expandable cryptographic operations. The framework itself makes extensive use of it internally, for instance, to safeguard OAuth state, CSRF tokens, and authentication cookies. This post describes how to use ASP.NET Core's Data Protection APIs to safeguard your private information.

The Data Protection API: What is it?
ASP.NET Core's Data Protection API is a cryptography framework made to:

  • Encrypt and decrypt data, such as tokens and connection strings.
  • Securely handle keys (with support for key rotation).
  • Assure confidentiality and resistance to tampering.
  • Connect with ASP.NET Core components with ease.

You depend on a managed service that takes care of algorithm selection, key management, and lifetime automatically rather than handling cryptography by yourself.

Setting Up Data Protection in ASP.NET Core
The Data Protection service is registered within Program.cs or Startup.cs.
var builder = WebApplication.CreateBuilder(args);

// Register Data Protection services
builder.Services.AddDataProtection();

builder.Services.AddControllers();
var app = builder.Build();
app.MapControllers();
app.Run();

This sets up the Data Protection system with in-memory key storage (by default).

Protecting and Unprotecting Data
Create a service that uses the IDataProtector interface:
using Microsoft.AspNetCore.DataProtection;

public class EncryptionService
{
    private readonly IDataProtector _protector;

    public EncryptionService(IDataProtectionProvider provider)
    {
        // Create a protector with a unique purpose string
        _protector = provider.CreateProtector("MyApp.DataProtection.Demo");
    }

    public string Protect(string plainText)
    {
        return _protector.Protect(plainText);
    }

    public string Unprotect(string protectedData)
    {
        return _protector.Unprotect(protectedData);
    }
}

Register it in Program.cs:
builder.Services.AddScoped<EncryptionService>();

Usage in a controller:
[ApiController]
[Route("api/[controller]")]
public class SecureController : ControllerBase
{
    private readonly EncryptionService _encryptionService;

    public SecureController(EncryptionService encryptionService)
    {
        _encryptionService = encryptionService;
    }

    [HttpGet("protect")]
    public string ProtectData(string input)
    {
        return _encryptionService.Protect(input);
    }

    [HttpGet("unprotect")]
    public string UnprotectData(string input)
    {
        return _encryptionService.Unprotect(input);
    }
}

Persisting Keys (Production Scenarios)
By default, keys are stored in-memory and lost when the app restarts. For production, configure persistent key storage.

File System Storage
builder.Services.AddDataProtection()
    .PersistKeysToFileSystem(new DirectoryInfo(@"C:\keys"))
    .SetApplicationName("MyApp");

Azure Blob Storage
builder.Services.AddDataProtection()
    .PersistKeysToAzureBlobStorage(
        new Uri("https://<account>.blob.core.windows.net/keys/key.xml"),
        new DefaultAzureCredential());


Redis (for multiple instances)
builder.Services.AddDataProtection()
    .PersistKeysToStackExchangeRedis(connectionMultiplexer, "DataProtection-Keys");


Key Management and Rotation

  • Keys are automatically rotated every 90 days (configurable).
  • Old keys are retained for decrypting data.
  • You can manually configure key lifetimes:

builder.Services.AddDataProtection()
    .SetDefaultKeyLifetime(TimeSpan.FromDays(30));


Common Use Cases

  • Protecting sensitive settings (e.g., API keys).
  • Encrypting tokens or IDs before sending them in URLs.
  • Securing cookies and session state (handled automatically).
  • Multi-instance apps (persist keys to shared storage).

Best Practices

  • Always persist keys in production.
  • Use a unique purpose string for each protected data type.
  • Store keys in secure locations (Azure Key Vault, Blob Storage, Redis).
  • Rotate keys regularly.
  • Never hardcode secrets—use environment variables or secret managers.

Conclusion
The ASP.NET Core Data Protection API provides a secure and developer-friendly way to handle encryption without needing deep cryptography knowledge. Whether you’re protecting sensitive values in configuration, encrypting tokens, or securing cookies, the Data Protection system ensures your app stays resilient against common cryptographic pitfalls. With persistent key storage, key rotation, and integration with cloud services, it’s ready for enterprise-grade applications.