net Core Data Protection 数据保护 加密 编码 哈希 FromServices
》》》 通过构造函数 获取服务
[Route("api/[controller]")][ApiController]public class DataProtectController : ControllerBase{[HttpGet]public string Info(){return "zen";}// [FromServices] 自动获取 builder.Services.AddDataProtection()注册的服务[HttpGet]public string Info1([FromServices] IDataProtectionProvider provider){string str = "资源文件";string resultStr = string.Empty;var protector = provider.CreateProtector("密钥11");//加密resultStr = protector.Protect(str);//解码 一般加密在另外的类,解码 在这里 //密钥 存在框架自己存起来啦resultStr = protector.UnProtect(resultStr );return resultStr;}}
数据保护 API
using Microsoft.AspNetCore.DataProtection;namespace ZenOAPI.Common
{public class DataProtectionHelper{private readonly IDataProtectionProvider _dataProtectionProvider;public DataProtectionHelper(IDataProtectionProvider dataProtectionProvider){_dataProtectionProvider = dataProtectionProvider;}/// <summary>/// 加密/// </summary>/// <param name="textToEncrypt"></param>/// <param name="key"></param>/// <returns></returns>public string Encrypt(string textToEncrypt, string key){return _dataProtectionProvider.CreateProtector(key).Protect(textToEncrypt);}/// <summary>/// 解密/// </summary>/// <param name="cipherText"></param>/// <param name="key"></param>/// <returns></returns>public string Decrypt(string cipherText, string key){return _dataProtectionProvider.CreateProtector(key).Unprotect(cipherText);}}}