Lesson 4 of 8
Data Protection API - Encrypting Sensitive Data
ASP.NET Core's Data Protection API provides cryptographic operations with automatic key management, key rotation, and expiry - without managing encryption keys manually. Use it for: encrypting PII in the database, securing cookie payloads, and generating signed URL tokens.
Data Protection for PII Encryption
using Microsoft.AspNetCore.DataProtection;
// ━━ Registration ━━
builder.Services
.AddDataProtection()
.PersistKeysToFileSystem(new DirectoryInfo("/etc/myapp/keys")) // in production: Azure Blob
.ProtectKeysWithAzureKeyVault(new Uri("https://myvault.vault.azure.net/keys/dataprotection"), new DefaultAzureCredential())
.SetApplicationName("MyApp") // isolates keys between apps
.SetDefaultKeyLifetime(TimeSpan.FromDays(90)); // rotate keys every 90 days
// ━━ Creating purpose-specific protectors ━━
// 'Purpose' scopes the key - token for email confirmation can't decrypt a PII field
public class SensitiveDataService(IDataProtectionProvider provider)
{
// Each 'purpose' gets its own derived key
private readonly IDataProtector _piiProtector =
provider.CreateProtector("user.pii.v1");
private readonly ITimeLimitedDataProtector _tokenProtector =
provider.CreateProtector("email.confirmation.v1").ToTimeLimitedDataProtector();
// ━━ Encrypt PII before storing in DB ━━
public string EncryptPII(string plaintext) =>
_piiProtector.Protect(plaintext);
public string DecryptPII(string ciphertext) =>
_piiProtector.Unprotect(ciphertext); // throws CryptographicException if tampered
// ━━ Time-limited tokens (email confirmation, password reset) ━━
public string CreateEmailToken(string email, TimeSpan validity) =>
_tokenProtector.Protect(email, lifetime: validity);
public (bool Success, string? Email) ValidateEmailToken(string token)
{
try
{
var email = _tokenProtector.Unprotect(token, out var expiry);
return (true, email);
}
catch (Microsoft.AspNetCore.DataProtection.Pkcs.InvalidProtectionDataException)
{
return (false, null); // tampered
}
catch (Microsoft.Security.Application.AntiXssEncoder)
{
return (false, null); // expired
}
catch (Exception)
{
return (false, null); // expired or invalid
}
}
}
// ━━ Encrypting SSN/DOB in DB ━━
public class CustomerService(SensitiveDataService dataProtection, AppDbContext db) where AppDbContext : class
{
public async Task UpdateSsnAsync(Guid customerId, string ssn, CancellationToken ct)
{
// ✅ Store BCrypt hash for verification
// ✅ Store AES-encrypted value for future retrieval (reversible)
var encryptedSsn = dataProtection.EncryptPII(ssn);
// store encryptedSsn in DB → even if DB is breached, SSNs are encrypted
}
}
class AppDbContext { }Tip
Tip
Practice Data Protection API Encrypting Sensitive Data in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
.NET provides a unified platform for building various application types
Practice Task
Note
Practice Task - (1) Write a working example of Data Protection API Encrypting Sensitive Data from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Data Protection API Encrypting Sensitive Data is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.
Finished this lesson?