C#配置文件加密解密的實(shí)現(xiàn)方案
方案核心:使用Windows數(shù)據(jù)保護(hù)API (DPAPI) 或 托管封裝
1. 最簡單實(shí)現(xiàn):使用ProtectedData類(DPAPI封裝)
DPAPI是Windows內(nèi)置的數(shù)據(jù)保護(hù)接口,無需管理密鑰,非常適合單機(jī)應(yīng)用。
using System.Security.Cryptography;
using System.Text;
public static class SimpleConfigProtector
{
// 加密字符串
public static string Encrypt(string plainText)
{
byte[] plainBytes = Encoding.UTF8.GetBytes(plainText);
byte[] encryptedBytes = ProtectedData.Protect(
plainBytes,
entropy: null, // 可選的附加熵值,增加安全性
scope: DataProtectionScope.CurrentUser // 或 LocalMachine
);
return Convert.ToBase64String(encryptedBytes);
}
// 解密字符串
public static string Decrypt(string encryptedText)
{
byte[] encryptedBytes = Convert.FromBase64String(encryptedText);
byte[] plainBytes = ProtectedData.Unprotect(
encryptedBytes,
entropy: null,
scope: DataProtectionScope.CurrentUser
);
return Encoding.UTF8.GetString(plainBytes);
}
}2. 配置文件集成方案
appsettings.json (原始)
{
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Database=MyDB;User=sa;Password=MyPass123;"
},
"ApiKey": "abc123def456"
}appsettings.json (加密后)
{
"ConnectionStrings": {
"DefaultConnection": "AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAAA0IAAAAAAA... (加密文本)"
},
"ApiKey": "AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAAA0IAAAAAAA..."
}配置讀取類
public class AppSettings
{
private readonly IConfiguration _configuration;
public AppSettings(IConfiguration configuration)
{
_configuration = configuration;
}
public string GetConnectionString()
{
var encrypted = _configuration.GetConnectionString("DefaultConnection");
return SimpleConfigProtector.Decrypt(encrypted);
}
public string GetApiKey()
{
var encrypted = _configuration["ApiKey"];
return SimpleConfigProtector.Decrypt(encrypted);
}
}3. 一鍵加密工具(控制臺應(yīng)用)
// ConfigEncryptor.cs
class Program
{
static void Main(string[] args)
{
Console.WriteLine("=== 配置文件加密工具 ===");
Console.Write("輸入要加密的文本: ");
string plainText = Console.ReadLine();
string encrypted = SimpleConfigProtector.Encrypt(plainText);
Console.WriteLine($"加密結(jié)果: {encrypted}");
Console.Write("是否測試解密? (y/n): ");
if (Console.ReadKey().Key == ConsoleKey.Y)
{
string decrypted = SimpleConfigProtector.Decrypt(encrypted);
Console.WriteLine($"\n解密結(jié)果: {decrypted}");
}
}
}方案優(yōu)勢與注意事項(xiàng)
優(yōu)點(diǎn)
- 零密鑰管理:DPAPI自動處理密鑰存儲
- 按用戶/機(jī)器隔離:
CurrentUser范圍防止其他用戶解密 - 無需外部依賴:僅需
System.Security.Cryptography - 防篡改:加密后的Base64字符串無法直接解讀
注意事項(xiàng)
DataProtectionScope選項(xiàng):
CurrentUser:只有當(dāng)前登錄用戶可解密LocalMachine:本機(jī)所有用戶可解密(安全性較低)
部署限制:
- DPAPI加密的內(nèi)容不能跨計(jì)算機(jī)解密
- 如需多服務(wù)器部署,考慮使用證書加密或Azure Key Vault
加密提示:首次運(yùn)行時(shí)可自動加密配置文件
// 啟動時(shí)檢查并加密配置
if (!IsEncrypted(configValue))
{
string encrypted = SimpleConfigProtector.Encrypt(configValue);
// 更新配置文件(謹(jǐn)慎操作)
}備選方案:如需跨平臺/跨機(jī)器加密
如果應(yīng)用需部署到多臺服務(wù)器,可采用基于證書的加密:
public static class CertificateProtector
{
public static string EncryptWithCertificate(string plainText, X509Certificate2 cert)
{
using RSA rsa = cert.GetRSAPublicKey();
byte[] plainBytes = Encoding.UTF8.GetBytes(plainText);
byte[] encryptedBytes = rsa.Encrypt(plainBytes, RSAEncryptionPadding.OaepSHA256);
return Convert.ToBase64String(encryptedBytes);
}
public static string DecryptWithCertificate(string encryptedText, X509Certificate2 cert)
{
using RSA rsa = cert.GetRSAPrivateKey();
byte[] encryptedBytes = Convert.FromBase64String(encryptedText);
byte[] plainBytes = rsa.Decrypt(encryptedBytes, RSAEncryptionPadding.OaepSHA256);
return Encoding.UTF8.GetString(plainBytes);
}
}最佳實(shí)踐建議
- 敏感配置項(xiàng):僅加密真正敏感的數(shù)據(jù)(密碼、密鑰),普通配置保持明文
- 開發(fā)/生產(chǎn)分離:開發(fā)環(huán)境可不加密,生產(chǎn)環(huán)境強(qiáng)制加密
- 備份原文:加密前備份原始配置,防止加密失敗
- 使用配置中心:大型系統(tǒng)建議使用Azure App Configuration/AWS Parameter Store
總結(jié)
對于大多數(shù)C#應(yīng)用,DPAPI方案是最簡單有效的配置保護(hù)方案:
- 開發(fā)簡單:僅需10行核心代碼
- 維護(hù)方便:無額外密鑰管理負(fù)擔(dān)
- 安全性足:滿足大部分應(yīng)用需求
- 無縫集成:與ASP.NET Core配置系統(tǒng)完全兼容
只需將敏感配置項(xiàng)替換為加密文本,在讀取時(shí)自動解密,即可實(shí)現(xiàn)"防改寫、防窺視"的安全目標(biāo)。
以上就是C#配置文件加密解密的實(shí)現(xiàn)方案的詳細(xì)內(nèi)容,更多關(guān)于C#配置文件加密解密的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
C#實(shí)現(xiàn)為Word文檔特定字符或句子添加邊框
開發(fā)者在處理Word文檔時(shí),常遇C# Word 文本邊框需求,本文將為大家詳細(xì)介紹C#如何使用Spire.Doc for .NET實(shí)現(xiàn)為Word文檔特定字符或句子添加邊框,希望對大家有所幫助2026-02-02
C#實(shí)現(xiàn)通過程序自動抓取遠(yuǎn)程Web網(wǎng)頁信息的代碼
C#實(shí)現(xiàn)通過程序自動抓取遠(yuǎn)程Web網(wǎng)頁信息的代碼...2007-04-04
WPF自定義控件綁定數(shù)據(jù)對象的最佳實(shí)踐
這篇文章主要介紹了WPF自定義控件數(shù)據(jù)綁定最佳實(shí)踐:直接使用DataContext簡單但易沖突,依賴屬性更清晰且適合列表場景,推薦在需回寫或列表使用時(shí)采用依賴屬性模式,需要的朋友可以參考下2025-09-09
C#定制Excel界面并實(shí)現(xiàn)與數(shù)據(jù)庫交互的方法
這篇文章主要介紹了C#定制Excel界面并實(shí)現(xiàn)與數(shù)據(jù)庫交互的方法的相關(guān)資料,需要的朋友可以參考下2015-11-11
C#中調(diào)用Windows?API實(shí)現(xiàn)文件操作的代碼實(shí)戰(zhàn)
在C#開發(fā)中,文件操作通常依賴于System.IO命名空間下的類,然而,這些類雖然封裝了豐富的功能,但在某些場景下存在限制,Windows?API是解決上述問題的終極方案,本文將通過真實(shí)項(xiàng)目級代碼,帶你從基礎(chǔ)到高級掌握如何在C#中調(diào)用Windows?API實(shí)現(xiàn)文件操作2025-08-08

