.NET Core 数据安全与加密实践:保护敏感信息的完整方案

发布时间:2026/8/11 18:07:42
.NET Core 数据安全与加密实践:保护敏感信息的完整方案 .NET Core 数据安全与加密实践保护敏感信息的完整方案数据安全是企业级应用的核心要求。本文将系统介绍 .NET Core 中保护敏感数据的完整方案涵盖数据传输加密、数据库存储加密、密钥管理和合规性要求。一、安全威胁模型┌──────────────────────────────────────────────────────────────┐ │ 攻击面 │ ├──────────────┬──────────────┬──────────────┬────────────────┤ │ 传输层 │ 应用层 │ 数据库层 │ 文件系统 │ │ 中间人攻击 │ SQL注入 │ 拖库攻击 │ 未授权访问 │ │ 嗅探 │ XSS/CSRF │ 备份泄露 │ 日志泄露 │ └──────────────┴──────────────┴──────────────┴────────────────┘二、数据传输安全强制 HTTPSvar builder WebApplication.CreateBuilder(args); // 生产环境强制 HTTPS if (!builder.Environment.IsDevelopment()) { builder.Services.AddHsts(options { options.MaxAge TimeSpan.FromDays(365); options.IncludeSubDomains true; options.Preload true; }); } var app builder.Build(); if (!app.Environment.IsDevelopment()) { app.UseHsts(); app.UseHttpsRedirection(); }安全响应头app.Use(async (context, next) { context.Response.Headers.Append(X-Content-Type-Options, nosniff); context.Response.Headers.Append(X-Frame-Options, DENY); context.Response.Headers.Append(X-XSS-Protection, 1; modeblock); context.Response.Headers.Append(Referrer-Policy, strict-origin-when-cross-origin); context.Response.Headers.Append(Content-Security-Policy, default-src self; script-src self unsafe-inline); await next(); });三、数据保护 API.NET Core 内置的 Data Protection API 是加密敏感数据的首选方案。// 注册数据保护服务 builder.Services.AddDataProtection() .PersistKeysToDbContextDataProtectionKeyContext() // 密钥持久化到数据库 .ProtectKeysWithAzureKeyVaultKey(new Uri(https://myvault.vault.azure.net/keys/dataprotection), new DefaultAzureCredential()) .SetDefaultKeyLifetime(TimeSpan.FromDays(90)) .SetApplicationName(MyApp);加密/解密字符串public class SensitiveDataService { private readonly IDataProtector _protector; public SensitiveDataService(IDataProtectionProvider provider) { _protector provider.CreateProtector(MyApp.SensitiveData); } public string Encrypt(string plainText) { if (string.IsNullOrEmpty(plainText)) return plainText; return _protector.Protect(plainText); } public string Decrypt(string cipherText) { if (string.IsNullOrEmpty(cipherText)) return cipherText; try { return _protector.Unprotect(cipherText); } catch (CryptographicException) { // 密钥轮换或数据损坏 return [DECRYPTION_FAILED]