注册 | 登录 忘记密码? 51cto首页 | 博客 | 论坛 | 招聘
热点文章 Mysql HA实现MYSQL的高可用
 帮助

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


2006-06-05 11:49:00
版权声明:原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。否则将追究法律责任。http://terrylee.blog.51cto.com/342737/67624
看了SHY520写的关于Data Access Application Block的文章,写得不错,忽略了一点就是如何去加密数据库连接字符串,这儿我简单的介绍一下。我们知道,在Enterprise Library1.1中加密连接字符串,需要依赖于Cryptography Application Block.NET Framework2.0中已经内置了这项功能,通过Configuration命名空间下的一些类来完成,支持两种类型的加密:
DPAPIProtectedConfigurationProvider:使用Windows Data Protection API (DPAPI)
RsaProtectedConfigurationProvider:使用RSA算法
下面来看一下具体的实现方法,假设已经有这样的一个配置文件:
<?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.添加对System.Configuration.dll的引用
2.在Program.cs中引入命名空间
using System.Configuration;
3.编写相关的代码:
/// <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);

    }

}
该方法的调用放在程序的主程序的入口点:
[STAThread]

static void Main()
{
    
// Protect the Connection Strings

    EncryptConfiguration();

    Application.Run(
new MainForm());

}
运行程序后,打开配置文件可以看到,连接字符串已经变成密文了。最后注意一点:加密的字符串在被加载到内存的时候解密。

本文出自 “TerryLee技术专栏” 博客,请务必保留此出处http://terrylee.blog.51cto.com/342737/67624





    文章评论
 
 

发表评论

昵   称:
验证码:  点击图片可刷新验证码  博客过2级,无需填写验证码
内   容: