.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. 定义加解密封装类
csharp 复制代码
using Microsoft.AspNetCore.DataProtection;

namespace EncrytionAndDecryption
{
    public class EncryptionService
    {
        private readonly IDataProtector _protector;

        // Constructor to initialize the IDataProtector using dependency injection
        public 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 data
        public string EncryptData(string plainText)
        {
            return _protector.Protect(plainText);
        }

        // Method to decrypt the encrypted data
        public string DecryptData(string encryptedData)
        {
            try
            {
                return _protector.Unprotect(encryptedData);
            }
            catch (Exception ex)
            {
                // If decryption fails (e.g., data is tampered or invalid), handle the exception
                return $"Decryption failed: {ex.Message}";
            }
        }
    }
}
  1. DI配置
csharp 复制代码
//第一次运行使用这个配置,会在运行路径生成一个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
csharp 复制代码
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 input
            var encryptedData = _encryptionService.EncryptData(sensitiveData);

            // For demonstration purposes, return the encrypted data to the view
            return Content($"Encrypted data: {encryptedData}");
        }

        // Action to decrypt previously encrypted data
        [HttpPost]
        public IActionResult DecryptData(string encryptedData)
        {
            // Call the DecryptData method to decrypt the encrypted data
            var decryptedData = _encryptionService.DecryptData(encryptedData);

            // For demonstration purposes, return the decrypted data to the view
            return Content($"Decrypted data: {decryptedData}");
        }
    }
}
  1. 发布
    发布之前将DI修改如下。并将之前生成的xml文件copy到发布路径下
csharp 复制代码
//当你第一次生成xml后,请使用下面的配置,避免重复生成xml,你只需要在你发布完成后,将上面步骤生成的xml拷贝到运行目录下即可
builder.Services.AddDataProtection()
            .PersistKeysToFileSystem(new DirectoryInfo(AppContext.BaseDirectory))  // Optional: Specify where to store keys
            .SetApplicationName("Ellis Test").DisableAutomaticKeyGeneration();
  1. 运行
bash 复制代码
dotnet EncrytionAndDecryption.dll --urls "http://localhost:8888"

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

设置存储key的路径

相关推荐
亦世凡华、5 小时前
掌握.NET Core后端发布流程,如何部署后端应用?
经验分享·.netcore·docker部署·程序发布
contact9712 小时前
.NET Core中的五种过滤器详解
.netcore·过滤器
以为不会掉头发的詹同学14 小时前
【 Avalonia UI 语言国际化 I18n】图文结合教学,保姆级教学,语言国际化就是这么简单(.Net C#)
开发语言·前端·c#·.netcore·用户界面
爱吃香蕉的阿豪3 天前
在c#中虚方法和抽象类的区别
深度学习·c#·.netcore
shepherd枸杞泡茶3 天前
第3章 .NETCore核心基础组件:3.1 .NET Core依赖注入
开发语言·c#·.net·.netcore
.NET快速开发框架3 天前
使用nvm管理node.js版本,方便vue2,vue3开发
vue·.netcore·常用工具·开发技术·rdif
csdn_aspnet5 天前
ASP.NET Core 使用 FileStream 将 FileResult 文件发送到浏览器后删除该文件
asp.net·.netcore
csdn_aspnet5 天前
ASP.NET Core SixLabors.ImageSharp v1.0 的图像实用程序类 web示例
asp.net·.netcore
csdn_aspnet5 天前
ASP.NET Core SixLabors.ImageSharp 位图图像创建和下载
asp.net·.netcore
时光追逐者8 天前
C#/.NET/.NET Core技术前沿周刊 | 第 24 期(2025年1.27-1.31)
microsoft·c#·.net·.netcore·微软技术