Web 应用程序通常需要将安全敏感数据存储。 Windows 桌面应用程序提供 DPAPI,但这并不适合 web 应用程序。 ASP.NET Core 数据保护堆栈提供一个简单、 易于使用的加密 API,开发人员可以使用来保护数据,包括密钥管理和旋转。
ASP.NET Core 数据保护堆栈旨在用作的长期替代<machineKey>在 ASP.NET 中的元素 1.x-4.x。 它旨在解决许多旧加密堆栈的不足之处同时为大多数现代应用程序可能会遇到的使用情况下提供开箱解决方案。
配置 ASP.NET Core 数据保护:
services.AddDataProtection() .PersistKeysToFileSystem(new DirectoryInfo($@"{AppDomain.CurrentDomain.BaseDirectory}/server/share/directory/"));运行应用目录\bin\Debug\netcoreapp2.2\server\share\directory下生成key 文件,注意:如果是多实例分部式部属,就应该将当前文件共享。
<?xml version="1.0" encoding="utf-8"?> <key id="b50ecc24-96e3-4010-80fa-5acc4ea0d19b" version="1"> <creationDate>2019-11-02T04:29:51.8142914Z</creationDate> <activationDate>2019-11-02T04:29:51.6587683Z</activationDate> <expirationDate>2020-01-31T04:29:51.6587683Z</expirationDate> <descriptor deserializerType="Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.AuthenticatedEncryptorDescriptorDeserializer, Microsoft.AspNetCore.DataProtection, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60"> <descriptor> <encryption algorithm="AES_256_CBC" /> <validation algorithm="HMACSHA256" /> <masterKey p4:requiresEncryption="true" xmlns:p4="http://schemas.asp.net/2015/03/dataProtection"> <!-- Warning: the key below is in an unencrypted form. --> <value>tZ0jZLC9iEHpTxelyUdQXsUvJZ7UO8oxRELCDHsnq1phlXdhF7AgvXL+sR3BkbqvpDbMHmqrfKNwdNJFEzdS/w==</value> </masterKey> </descriptor> </descriptor> </key>使用:
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.Mvc; namespace SaaS.AspNetCore.Sample.Controllers { public class DataProtectionController : Controller { private readonly IDataProtector _protector; public DataProtectionController(IDataProtectionProvider provider) { _protector = provider.CreateProtector("SaaS.AspNetCore.Sampl.v1"); } public IActionResult Index() { var plaintext = Guid.NewGuid().ToString(); var protectedPayload = _protector.Protect(plaintext); var unprotectedPayload = _protector.Unprotect(protectedPayload); return View(); } } }plaintext:加密后的密文
CfDJ8CTMDrXjlhBAgPpazE6g0ZuU-cwHnytuGROfdkCwW2CXX8OVk-b_iNBd-hljbHc-DCy3mmDMM1wq8xeX3Wape9l54mLnKTfBR0xXx-LV0sNx5jdN1pbQ-u1Gf0NcAiHLQkYU4aqMZ0nGbj8UrQigt3lQXjPSHPD2UqUVmI22aZ73
