您的位置:首页 > 数据库

Enterprise Library2.0中加密数据库连接字符串

2008-04-23 03:07 387 查看
看了SHY520写的关于Data Access Application Block的文章,写得不错,忽略了一点就是如何去加密数据库连接字符串,这儿我简单的介绍一下。我们知道,在Enterprise Library1.1中加密连接字符串,需要依赖于Cryptography Application Block。.NET Framework2.0中已经内置了这项功能,通过Configuration命名空间下的一些类来完成,支持两种类型的加密:
DPAPIProtectedConfigurationProvider:使用Windows Data Protection API (DPAPI)
RsaProtectedConfigurationProvider:使用RSA算法
下面来看一下具体的实现方法,假设已经有这样的一个配置文件:
.添加对System.Configuration.dll的引用


<?xml version="1.0" encoding="utf-8"?>




<configuration>




<configSections>




<section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null" />




</configSections>




<dataConfiguration defaultDatabase="QuickStarts" />




<connectionStrings>




<add name="QuickStarts" connectionString="Database=EntLibQuickStarts;Server=RJ-097;Integrated Security=SSPI;"




providerName="System.Data.SqlClient" />




</connectionStrings>




</configuration>



1



2.在Program.cs中引入命名空间3.编写相关的代码:


using System.Configuration;




/**//// <summary>




/// Author:TerryLee




/// From:http://terrylee.cnblogs.com




/// </summary>




static void EncryptConfiguration()






{


// 使用什么类型的加密




string provider = "RsaProtectedConfigurationProvider";




Configuration config = null;




config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);




// 加密连接字符串




ConfigurationSection section = config.ConnectionStrings;




if ((section.SectionInformation.IsProtected == false) &&




(section.ElementInformation.IsLocked == false))








{


section.SectionInformation.ProtectSection(provider);




section.SectionInformation.ForceSave = true;




config.Save(ConfigurationSaveMode.Full);




}


}
[align=left]该方法的调用放在程序的主程序的入口点:[/align]


[STAThread]




static void Main()






{


// Protect the Connection Strings




EncryptConfiguration();




Application.Run(new MainForm());




}
[align=left]运行程序后,打开配置文件可以看到,连接字符串已经变成密文了。最后注意一点:加密的字符串在被加载到内存的时候解密。[/align]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: