思想决定人生,态度改变一切

成功者找方法,失败者找借口! 做事先做人;安分做人,本分做事!

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
序言
开发者经常需要在配置文件中存储一些配置信息。比如,数据库联接字符串,用户名和密码等。(这就提出)一个要求,使用ASP.NET 1.x的时候,.net framework应该提供一些方法密或解密这些信息。庆幸的是,ASP.NET 2.0可以灵活的满足这一要求。这篇文章将会展示怎样用嵌入的工具和代码保护一个特定的配置节。

怎样加密配置文件?
ASP.NET 2.0允许你加密配置文件的一部分,来确保他们的安全(相对的)。这个特征通常被叫做受保护配置(Protected Configuration)。ASP.NET提供了两种方法来加密和解密配置文件

  • 在命令提示行中,通过ASPNET_REGIIS.EXE工具
  • 通过 configuration management 类

加密与解密通过两个受保护的提供者实现

  • RsaProtectedConfigurationProvider
  • DataProtectionConfigurationProvider

存储在可以在你的机器里的machine.config文件中找到这两个提供者。RsaProtectedConfigurationProvider是默认的提供者。下面的部分是machine.config中的相关标记

<configProtectedData
defaultProvider="RsaProtectedConfigurationProvider">
<providers>
<add name="RsaProtectedConfigurationProvider"
type="System.Configuration.RsaProtectedConfigurationProvider,
System.Configuration, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a"
description="Uses RsaCryptoServiceProvider to encrypt and decrypt"
keyContainerName="NetFrameworkConfigurationKey"
cspProviderName="" useMachineContainer="true" useOAEP="false" />
<add name="DataProtectionConfigurationProvider"
type="System.Configuration.DpapiProtectedConfigurationProvider,
System.Configuration, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a"
description="Uses CryptProtectData and CryptUnProtectData
Windows APIs to encrypt and decrypt" useMachineProtection="true"
keyEntropy="" />
</providers>
</configProtectedData>

使用ASPNET_REGIIS.EXE加密一个配置节

让我们来看看如何使用ASPNET_REGIIS.EXE工具来加密<connectionStrings>配置节。

用VS.Net建立一个网站叫做EncryptTest,加入一个web.config文件。然后加入如下的<connectionStrings>配置节:

<connectionStrings>
<add name="connstr" connectionString=
"data source=.\sqlexpress;initial catalog=
northwind;integrated security=true" />
</connectionStrings>

我们简单的加入了一个联接字符串,指向了Northwind数据库。然后打开default.aspx文件,拖拽一个GridView控件,并在Page_Load中输入如下代码:

protected void Page_Load(object sender, EventArgs e)
{
string strConn = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;
SqlDataAdapter da = new SqlDataAdapter("select * from customers", strConn);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
} 

这段代码里,我们用ConfigurationManager类从<connectionStrings>配置节读取了联接字符串。这里用们有意的用了手动的方法代替了SqlDataSource空间,就是为了证明内置的类ConfigurationManager自动的机密了加密版本的联机字符串。

 现在打开Visual Studio 2005命令提示,执行下面的命令:
aspnet_regiis -pe "connectionStrings" -app "/encrypttest"
-pe开关用来指定web.config中需要加密的节(我们的例子里是connectionStrings)。
-app开关用来指定IIS里面的虚拟路径

执行以后,如果你再查看一下web.config文件,你会看到这样的情形:

<connectionStrings configProtectionProvider=
"RsaProtectedConfigurationProvider">
<EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element"
xmlns="http://www.w3.org/2001/04/xmlenc#">
<EncryptionMethod Algorithm=
"http://www.w3.org/2001/04/xmlenc#tripledes-cbc" />
<KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
<EncryptedKey xmlns="http://www.w3.org/2001/04/xmlenc#">
<EncryptionMethod Algorithm=
"http://www.w3.org/2001/04/xmlenc#rsa-1_5" />
<KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
<KeyName>Rsa Key</KeyName>
</KeyInfo>
<CipherData>
<CipherValue>NW4gFUtlA3XkbKu42FQ3kYV8EKmwzy9r53vrI2rjV
ZFqjsr00/MwS6TWqjnsguN09kWvNIrbfWu5+Gi+DLFhYnGm2NcuaCy
Vic8f5e0Q8u3E7zk2MegZmiri5bSELE1fZneWz4oFb+MHqA94ZO3Be
XBlocou6ydtmJPXZCqLsDQ=</CipherValue>
</CipherData>
</EncryptedKey>
</KeyInfo>
<CipherData>
<CipherValue>T2fswq6Rt7g7VSNUnoe4kNFGSluWCBReQf3DRbXao/
sWaWs4mrJAI6Xy0zNDHY5pKXUUF9Kep2wG84rMVx0QtLIUjBaUKCnrm
Eb+53oYNPjN4Kf5zcPyWoaWwcus4LnJYNtg3oGJUvavZ0tjGXH9+5gB
w/xMrtfDcYAIom9l/IMcO92BKrvimjn/k4Mr8VXxGpvdMkAC3+e6dtW
JeUgQGpepO+RNpWymB5kWj38LjMQ=</CipherValue>
</CipherData>
</EncryptedData>
</connectionStrings>



这个工具已经用RsaProtectedConfigurationProvider(默认的提供者)加密了connectionStrings节点,
并且将加密过的标签返回给配置文件。你还可以指定具体的Protected Configuration Provider(加密保护配置提供者),
使用-prov开关来指定。很简单,不是么?

现在,浏览你的web页面。这个web页面将会在GridView标记里正确的显示Customers表的内容,这说明ConfigurationManager类
在读取连接字符串的时候自动解密了其中的信息。

使用ASPNET_REGIIS.EXE解密配置节

如果你需要在开发过程中对连接串进行些改动要怎么办?不用担心,ASPNET_REGIIS.EXE工具同样支持解密节点,仅仅需要执行
下面的命令就会恢复到你原来的未加密的版本。
aspnet_regiis -pd "connectionStrings" -app "/encrypttest"
唯一的区别就是,我们用-pd开关代替了-pa开关。

Encryption and decrypting via code

The task of encrypting and decrypting web.config can also be achieved via code. Let's see how.

Add a new web form to the same web site and design it as shown below:

通过代码加密与解密 
加密与解密web.config功能同样可以通过代码来完成。让我们看看怎样完成的。
在同样的站点下加入一个新的web页面,并且设计成下面的样子

在"Encrypt Connection String"按钮的Click事件中加入如下代码:

protected void Button1_Click(object sender, EventArgs e)
{
Configuration config = WebConfigurationManager.
OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection section = config.ConnectionStrings;
if (!section.SectionInformation.IsProtected)
{
section.SectionInformation.ProtectSection
("RsaProtectedConfigurationProvider");
section.SectionInformation.ForceSave = true;
config.Save(ConfigurationSaveMode.Modified);
}
}
 

如果你不是很熟需怎样修改web.config的内容,下面的这篇文章应该对你有帮助

通过程序修改Web.config文件的内容


这段代码的上半部分是打开并修改web.config文件。然后找到ConnectionStrings配置节。
然后,粗体字的部分是非常重要的。ProtectSection()方法指定了你用来加密节点的Protected Configuration Provider(保护配置供应者),
然后用这个供应者加密了下一行的节点。
代码最后将结果保存。
解密配置节的工作和加密类似:
protected void Button2_Click(object sender, EventArgs e)
{
Configuration config = WebConfigurationManager.
OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection section = config.ConnectionStrings;
if (section.SectionInformation.IsProtected)
{
section.SectionInformation.UnprotectSection();
section.SectionInformation.ForceSave = true;
config.Save(ConfigurationSaveMode.Modified);
}
}
这里我们用UnprotectSection()方法回复到未加密的版本。
概述
The encryption and decryption can be done in two ways - using ASPNET_REGIIS command line tool or programmatically.
ASP.NET 2.0让保护你的web.config文件变得非常容易,它允许你通过加密的方式进行保护。
无论是加密还是解密都有两种办法--使用ASPNET_REGIIS命令行工具 或 程序控制
posted on 2007-04-01 00:14  投石问路  阅读(574)  评论(1编辑  收藏  举报