当前位置: 首页 > news >正文

.netCore WebAPI中字符串加密与解密

In today’s digital landscape, securing sensitive information is more critical than ever. If you’re using ASP.NET Core, you might store configuration settings in appsettings.json. However, hardcoding sensitive data like connection strings or API keys in plain text can expose your application to serious risks.

ASP.NET Core has built-in support for encryption through its Data Protection API. This can be used to secure sensitive information. The Data Protection API in ASP.NET Core allows you to easily encrypt and decrypt sensitive data, such as user information, and configuration settings. This article will guide you through encrypting and decrypting sensitive information using ASP.NET Core Data Protection API in your application.

ASP.NET Core includes the Data Protection API by default. You do not need to install additional packages unless you’re storing keys externally (like Azure or Redis). Below are detailed steps for using this Data Protection API to protect sensitive information.

  1. 定义加解密封装类
using Microsoft.AspNetCore.DataProtection;namespace EncrytionAndDecryption
{public class EncryptionService{private readonly IDataProtector _protector;// Constructor to initialize the IDataProtector using dependency injectionpublic EncryptionService(IDataProtectionProvider provider){// 'MyPurpose' is a unique string that ensures different protection policies for different purposes_protector = provider.CreateProtector("MyPurpose");}// Method to encrypt plain text datapublic string EncryptData(string plainText){return _protector.Protect(plainText);}// Method to decrypt the encrypted datapublic string DecryptData(string encryptedData){try{return _protector.Unprotect(encryptedData);}catch (Exception ex){// If decryption fails (e.g., data is tampered or invalid), handle the exceptionreturn $"Decryption failed: {ex.Message}";}}}
}
  1. DI配置
//第一次运行使用这个配置,会在运行路径生成一个xml的key文件
builder.Services.AddDataProtection().PersistKeysToFileSystem(new DirectoryInfo(AppContext.BaseDirectory))  // Optional: Specify where to store keys.SetApplicationName("Ellis Test");//当你第一次生成xml后,请使用下面的配置,避免重复生成xml,你只需要在你发布完成后,将上面步骤生成的xml拷贝到运行目录下即可
//builder.Services.AddDataProtection()
//            .PersistKeysToFileSystem(new DirectoryInfo(AppContext.BaseDirectory))  // Optional: Specify where to store keys
//            .SetApplicationName("Ellis Test").DisableAutomaticKeyGeneration();// Register the EncryptionService for dependency injection
builder.Services.AddScoped<EncryptionService>();
  1. 添加controller
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;namespace EncrytionAndDecryption.Controllers
{[Route("api/[controller]/[action]")][ApiController]public class EnDeController : ControllerBase{private readonly EncryptionService _encryptionService;public EnDeController(EncryptionService encryptionService){_encryptionService = encryptionService;}// Action to encrypt sensitive data[HttpPost]public IActionResult EncryptData(string sensitiveData){// Call the EncryptData method to encrypt the inputvar encryptedData = _encryptionService.EncryptData(sensitiveData);// For demonstration purposes, return the encrypted data to the viewreturn Content($"Encrypted data: {encryptedData}");}// Action to decrypt previously encrypted data[HttpPost]public IActionResult DecryptData(string encryptedData){// Call the DecryptData method to decrypt the encrypted datavar decryptedData = _encryptionService.DecryptData(encryptedData);// For demonstration purposes, return the decrypted data to the viewreturn Content($"Decrypted data: {decryptedData}");}}
}
  1. 发布
    发布之前将DI修改如下。并将之前生成的xml文件copy到发布路径下
//当你第一次生成xml后,请使用下面的配置,避免重复生成xml,你只需要在你发布完成后,将上面步骤生成的xml拷贝到运行目录下即可
builder.Services.AddDataProtection().PersistKeysToFileSystem(new DirectoryInfo(AppContext.BaseDirectory))  // Optional: Specify where to store keys.SetApplicationName("Ellis Test").DisableAutomaticKeyGeneration();
  1. 运行
dotnet EncrytionAndDecryption.dll --urls "http://localhost:8888"

https://github.com/xdqt/asp.net-core/tree/master/EncrytionAndDecryption

设置存储key的路径

http://www.lryc.cn/news/479759.html

相关文章:

  • Next.js + Move 石头剪刀布
  • [面试]关于Redis 的持久化你了解吗
  • Systemd:tmpfiles
  • 【Flutter 内嵌 android 原生 View以及相互跳转】
  • python externally-managed-environment 外部管理环境
  • 前端 | MYTED单篇TED词汇学习功能优化
  • 64 mysql 的 表锁
  • 【计网不挂科】计算机网络期末考试——【选择题&填空题&判断题&简述题】题库(1)
  • ajax关于axios库的运用小案例
  • 微搭低代码入门01变量
  • 盘点2024年10款视频剪辑,哪款值得pick!!
  • 苹果手机照片批量删除:一键清理,释放空间
  • 《AI 大模型:重塑软件开发新生态》
  • uniapp(API-Promise 化)
  • 【考研数学 - 数二题型】考研数学必吃榜(数二)
  • Redis生产问题(缓存穿透、击穿、雪崩)——针对实习面试
  • android openGL中模板测试、深度测试功能的先后顺序
  • CCF PTA 编程培训师资认证2021年7月真题- C++兑换礼品
  • 火山引擎云服务docker 安装
  • 【taro react】 ---- 常用自定义 React Hooks 的实现【六】之类渐入动画效果的轮播
  • 基础算法练习--滑动窗口(已完结)
  • 深度学习经典模型之ZFNet
  • Linux系统-ubuntu系统安装
  • 2-Ubuntu/Windows系统启动盘制作
  • 你使用过哪些MySQL中复杂且使用不频繁的函数?
  • Redis-07 Redis哨兵
  • 7.qsqlquerymodel 与 qtableview使用
  • 状态模式(State Pattern)详解
  • ajax微信静默登录不起效不跳转问题
  • 参数估计理论