使用asp.net2.0或3.5编程加密、解密web.config中的配置信息

ASP.NET Configuration API 提供了加密、解密web.config中的配置片段(sections)支持。这为您保护隐私信息(如密码)提供了极大的便利。这篇文章中,我们将讨论如何加密、解密web.config中的sections。
 有两种方法加密配置片段(sections),微软提供了两个providers:DPAPI(Windows Data Protection API)及RSA provider。其中RAS provider为默认。它使用RSA密钥,并拥有公钥和私钥。而DPAPI provider 则使用机器编译内规范密钥(built-in machine-specific key)。下面让我们使用RSA方法加密配置文件中的sections。
1: 打开 Visual Studio > 文件 > 网站> 选择语言(C# or Visual Basic) 及位置创建新的asp.net网站。
2: 然后为项目增加web.config 文件。右击项目>增加新项>WEB配置文件。
打开web.config文件,在<configuration>标记中增加以下所示行:
<configuration>
      <appSettings>
            <add key="var1" value="SomeValue"/>
      </appSettings>
      <connectionStrings>
 <add name="MyConnString" connectionString="Data Source=(local);Initial Catalog=Northwind;Integrated Security=True;" />
 </connectionStrings>
      <system.web>...
</configuration>
 
3: 然后在页面中添加两个按钮。命名为:btnEncrypt 和 btnDecrypt. 我们将使用这两个按钮来加密、解密web.config中sections。为两个按钮添加以下button click事件代码: 
C#
string provider = "RSAProtectedConfigurationProvider";
string section = "connectionStrings";
 
protected void btnEncrypt_Click(object sender, EventArgs e)
{
try
{
    Configuration confg = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
    ConfigurationSection confStrSect = confg.GetSection(section);
    if (confStrSect != null)
    {
        confStrSect.SectionInformation.ProtectSection(provider);
        confg.Save();
    }
    // the encrypted section is automatically decrypted!!
    Response.Write("Configuration Section " + "<b>" +
        WebConfigurationManager.ConnectionStrings["MyConnString"].ConnectionString + "</b>" + " is automatically decrypted");
}
catch (Exception ex)
{
   
}       
}
 
protected void btnDecrypt_Click(object sender, EventArgs e)
{
try
{
    Configuration confg = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
    ConfigurationSection confStrSect = confg.GetSection(section);
    if (confStrSect != null && confStrSect.SectionInformation.IsProtected)
    {
        confStrSect.SectionInformation.UnprotectSection();
        confg.Save();
    }
 
}
catch (Exception ex)
{
 
}
}
如果你在文件系统中运行这个程序,当你关闭程序,Visual将会弹出以下的提示信息:"文件在外部被修改,是否重新载入?" 点击“是”即可查看.
posted @ 2009-07-27 13:53  周宏伟  阅读(289)  评论(0编辑  收藏  举报