在开发C#应用程序时,我们经常使用JSON格式的配置文件(如appsettings.json)来存储数据库连接字符串、API密钥、密码等敏感信息。然而,这些明文配置一旦泄露,将带来严重的安全风险。本文将详细讲解如何在C#项目中对JSON配置文件进行加密与解密,即使你是编程新手,也能轻松上手!

默认情况下,.NET Core/.NET 5+ 使用的appsettings.json是以明文形式存储的。如果服务器被入侵或源码意外公开,攻击者可直接读取敏感数据。通过C# JSON配置文件加密,我们可以有效防止此类风险,提升应用安全性。
我们将采用对称加密算法(如AES)对整个JSON配置文件进行加密。程序启动时,先读取加密后的配置文件,再用密钥解密为原始JSON内容,最后加载到IConfiguration中供应用程序使用。
首先,在你的C#项目中添加一个名为EncryptionHelper.cs的工具类:
using System;using System.IO;using System.Security.Cryptography;using System.Text;public static class EncryptionHelper{ private static readonly byte[] Salt = Encoding.UTF8.GetBytes("your-unique-salt-here"); // 建议使用更复杂的盐值 public static string Encrypt(string plainText, string password) { using var aes = Aes.Create(); var pdb = new Rfc2898DeriveBytes(password, Salt, 10000, HashAlgorithmName.SHA256); aes.Key = pdb.GetBytes(32); aes.IV = pdb.GetBytes(16); using var ms = new MemoryStream(); using var cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write); using (var sw = new StreamWriter(cs)) { sw.Write(plainText); } return Convert.ToBase64String(ms.ToArray()); } public static string Decrypt(string cipherText, string password) { using var aes = Aes.Create(); var pdb = new Rfc2898DeriveBytes(password, Salt, 10000, HashAlgorithmName.SHA256); aes.Key = pdb.GetBytes(32); aes.IV = pdb.GetBytes(16); using var ms = new MemoryStream(Convert.FromBase64String(cipherText)); using var cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Read); using var sr = new StreamReader(cs); return sr.ReadToEnd(); }}注意:实际项目中,密码(password)不应硬编码在代码中,建议从环境变量、Azure Key Vault 或 Windows DPAPI 等安全来源获取。
假设你有一个原始的appsettings.json:
{ "ConnectionStrings": { "DefaultConnection": "Server=myServer;Database=myDB;User Id=myUser;Password=myPass;" }, "ApiKeys": { "WeatherApiKey": "abc123xyz" }}编写一个控制台程序或使用单元测试,调用EncryptionHelper.Encrypt方法,将上述JSON内容加密,并保存为appsettings.encrypted:
string originalJson = File.ReadAllText("appsettings.json");string encrypted = EncryptionHelper.Encrypt(originalJson, "MyStrongPassword123!");File.WriteAllText("appsettings.encrypted", encrypted);修改Program.cs(以.NET 6+为例),在构建主机前先解密配置:
using Microsoft.Extensions.Configuration;using Microsoft.Extensions.Hosting;var encryptedConfig = File.ReadAllText("appsettings.encrypted");var decryptedJson = EncryptionHelper.Decrypt(encryptedConfig, "MyStrongPassword123!");var config = new ConfigurationBuilder() .AddJsonStream(new MemoryStream(Encoding.UTF8.GetBytes(decryptedJson))) .Build();var builder = Host.CreateApplicationBuilder(args);builder.Configuration.AddConfiguration(config);// 继续注册服务...var host = builder.Build();host.Run();.encrypted文件不被提交到Git等版本控制系统(添加到.gitignore)。通过本文的教程,你已经掌握了如何在C#项目中实现.NET配置加密,有效保护敏感的JSON配置数据。无论是Web API、桌面应用还是微服务,这种技术都能显著提升你的JSON数据保护C#能力。记住,安全不是一次性任务,而是持续的过程。希望这篇关于C#配置文件安全的指南对你有所帮助!
本文由主机测评网于2025-12-04发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://www.vpshk.cn/2025122702.html