65.9K
CodeProject 正在变化。 阅读更多。
Home

在 App.config 中加密连接字符串的密码

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.50/5 (3投票s)

2012 年 9 月 18 日

CPOL

2分钟阅读

viewsIcon

31039

展示如何在 .NET 应用程序的 App.config 中仅加密 MS SQL 连接字符串的密码。

引言

本文档简要介绍了如何轻松加密/保护 app.config 文件中连接字符串的密码段。 相同的技术可以轻松地用于隐藏 .NET 配置文件中**应用程序**类型设置的任何其他属性。

背景

过去,我曾使用安全提供程序来保护许多 .NET 应用程序的 app.config 中的连接字符串。 使用内置机制会隐藏整个部分,而不是仅一个属性。 最近,我遇到了一种情况,隐藏整个部分不可接受,因此我只需要隐藏密码。 在网上搜索后,我决定采用手工制作的解决方案。

由于 app.config 是一个纯 XML 文件,我决定将其视为 XML 文件。 我的解决方案将 app.config 加载到 XmlDocument 中,使用 XPath 查找相关节点(connectionString),将连接字符串加载到 SqlConnectionStringBuilder 中,加密密码,从构建器获取更新后的连接字符串,更新 XmlDocument,然后将其保存回原始文件路径。

使用代码

下面的代码不是完整的实现,您需要完全实现加密和解密方法。 解密方法应在无法解密密码或密码未加密时返回空字符串或 null。

您应该只在应用程序启动过程的尽可能早的时候调用 GetConnectionString 一次,并将连接字符串存储在属性或其他您以后可以轻松访问的变量中。

class Program
{
 static void Main(string[] args)
 {
  string connString = GetConnectionString("dbConn");
  Console.WriteLine(connString);
  Console.ReadKey();
 }
 static string GetConnectionString(string connName)
 {
  string connString = string.Empty;
  string configPath = Process.GetCurrentProcess().MainModule.FileName + ".config";
  XmlDocument doc = new XmlDocument();
  doc.Load(configPath);
  XmlNode node = doc.SelectSingleNode("configuration/connectionStrings/add[@name = \"" + connName + "\"]");
  if (node != null)
  {
   XmlAttribute attr = node.Attributes["connectionString"];
   if (attr != null)
   {
    SqlConnectionStringBuilder csb = new SqlConnectionStringBuilder(attr.Value);
    string clearPass = Decrypt(csb.Password);
    if (string.IsNullOrEmpty(clearPass))
    {
     connString = csb.ToString();
     csb.Password = Encrypt(csb.Password);
     attr.Value = csb.ToString();
     doc.Save(configPath);
    }
    else
    {
     csb.Password = clearPass;
     connString = csb.ToString();
    }                    
   }
  }
  return connString;
 }
static string Encrypt(string value)
 {
  throw new NotImplementedException();
 }
 static string Decrypt(string value)
 {
  throw new NotImplementedException();
 }
} 

关注点

  • 最重要的是,您可以随时用新的密码覆盖加密的密码,并在应用程序下次启动时对其进行加密。
  • 此解决方案在升级情况下效果很好,其中连接字符串和密码不安全,在首次运行时,它将无缝加密现有的密码。
  • 仅保护密码允许用户查看字符串中的其他非关键数据。
  • 如果您在此代码运行后使用 ConfigurationManager 获取字符串,则您的连接将失败,因为密码已加密。
© . All rights reserved.