在C#开发的应用程序中,数据库连接字符串包含数据库地址、登录账号、密码等敏感信息,如果直接以明文形式存储在app.config或web.config中,一旦配置文件被非法获取,就可能导致数据库被恶意访问。因此实现连接字符串加密是提升应用安全性的重要环节,下面介绍几种常用的实现方法。

方法一:使用Windows DPAPI加密
DPAPI是Windows系统提供的原生数据保护接口,无需开发者自己管理密钥,加密后的数据只能在同一台机器的同一用户上下文下解密,适合单机部署的应用场景。
首先需要在项目中引用System.Security.Cryptography命名空间,加密和解密的实现代码如下:
using System;
using System.Security.Cryptography;
using System.Text;
public class DpapiEncryptHelper
{
// 加密连接字符串
public static string EncryptConnectionString(string plainText)
{
if (string.IsNullOrEmpty(plainText))
return plainText;
// 将明文转为字节数组
byte[] plainBytes = Encoding.UTF8.GetBytes(plainText);
// 使用DPAPI加密,指定当前用户作用域
byte[] encryptedBytes = ProtectedData.Protect(plainBytes, null, DataProtectionScope.CurrentUser);
// 转为Base64字符串方便存储
return Convert.ToBase64String(encryptedBytes);
}
// 解密连接字符串
public static string DecryptConnectionString(string encryptedText)
{
if (string.IsNullOrEmpty(encryptedText))
return encryptedText;
// 将Base64字符串转回字节数组
byte[] encryptedBytes = Convert.FromBase64String(encryptedText);
// 使用DPAPI解密
byte[] plainBytes = ProtectedData.Unprotect(encryptedBytes, null, DataProtectionScope.CurrentUser);
// 转回明文
return Encoding.UTF8.GetString(plainBytes);
}
}
使用时只需要调用对应方法即可,加密后的字符串可以存储到配置文件中,程序启动时再解密使用。
方法二:使用.NET内置的配置节加密
.NET框架提供了对配置文件节点的加密支持,可以直接对connectionStrings节点进行加密,不需要自己写加密逻辑,适合使用标准配置文件的项目。
可以通过代码或者命令行工具实现加密,代码方式的实现如下:
using System.Configuration;
public class ConfigEncryptHelper
{
// 加密配置文件的连接字符串节点
public static void EncryptConnectionStrings(string configPath)
{
// 打开指定路径的配置文件
Configuration config = ConfigurationManager.OpenExeConfiguration(configPath);
// 获取连接字符串配置节
ConnectionStringsSection section = config.GetSection("connectionStrings") as ConnectionStringsSection;
if (section != null && !section.SectionInformation.IsProtected)
{
// 使用DPAPI保护提供程序加密,也可以换成其他提供程序
section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
// 保存配置修改
config.Save();
}
}
// 解密连接字符串节点
public static void DecryptConnectionStrings(string configPath)
{
Configuration config = ConfigurationManager.OpenExeConfiguration(configPath);
ConnectionStringsSection section = config.GetSection("connectionStrings") as ConnectionStringsSection;
if (section != null && section.SectionInformation.IsProtected)
{
// 移除保护,即解密
section.SectionInformation.UnprotectSection();
config.Save();
}
}
}
加密后配置文件中connectionStrings节点会变成加密后的密文,程序读取时会自动解密,不需要额外处理。
方法三:自定义对称加密算法
如果需要跨机器使用加密后的连接字符串,或者需要自己控制密钥,可以使用AES等对称加密算法实现,密钥需要妥善保管,避免泄露。
以AES算法为例,实现代码如下:
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
public class AesEncryptHelper
{
// 加密密钥,实际项目中需要妥善存储,不要硬编码
private static readonly byte[] Key = Encoding.UTF8.GetBytes("12345678901234567890123456789012"); // 32位密钥对应AES-256
private static readonly byte[] IV = Encoding.UTF8.GetBytes("1234567890123456"); // 16位初始化向量
// AES加密连接字符串
public static string EncryptConnectionString(string plainText)
{
if (string.IsNullOrEmpty(plainText))
return plainText;
using (Aes aes = Aes.Create())
{
aes.Key = Key;
aes.IV = IV;
ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter sw = new StreamWriter(cs))
{
sw.Write(plainText);
}
}
return Convert.ToBase64String(ms.ToArray());
}
}
}
// AES解密连接字符串
public static string DecryptConnectionString(string encryptedText)
{
if (string.IsNullOrEmpty(encryptedText))
return encryptedText;
using (Aes aes = Aes.Create())
{
aes.Key = Key;
aes.IV = IV;
ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(encryptedText)))
{
using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
{
using (StreamReader sr = new StreamReader(cs))
{
return sr.ReadToEnd();
}
}
}
}
}
}
方法选择建议
如果是单机部署的Windows应用,优先选择DPAPI或者.NET内置配置节加密,实现简单且不需要管理额外密钥;如果需要跨机器部署或者密钥需要自己控制,可以选择自定义对称加密算法,但要注意密钥的安全存储,避免密钥泄露导致加密失效。
无论选择哪种方法,都要避免将加密密钥硬编码在代码中,也不要将密钥和加密后的连接字符串放在同一个配置文件里,进一步提升安全性。
C#数据库连接字符串加密DPAPIConfigurationSection加密算法修改时间:2026-06-09 12:54:27