加密与解密Web.Config

来源:互联网 发布:数据库里boolean和bool 编辑:程序博客网 时间:2024/04/30 00:08

ASP.NET 3.5 中提供了对配置节直接加密的功能。在配置文件中有几处配置可能包含敏感信息,如<connectionStrings>节,它可能包含连接数据库的用户名和密码。<identity>节可能包含runtime 使用模拟账户的用户名和密码,甚至可能在配置文件的appSettings 中或在自定义节中包含共享Web Service 使用的密码。不管哪种情况,都不希望密码以明文的方式存放在配置文件中。本实例通过加密Web.Config 文件来提高文件的安全性,加密效果如图17.17 所示,在加密后还可以对Web.Config 文件进行解密,如图17.18 所示。


关 键技术
System.Configuration.SectionInformation 类对一个配置节的描述进行了抽象,使用它可以对Web.Config 文件进行加密或解密,下面将详细介绍如何使用该类对Web.Config 文件进行加密与解密。如果要加密一个配置节,只需要简单地使用SectionInformation 类的ProtectSection(提供程序)方法,传递想要使用的提供程序的名字来执行加密。当需要解密文件配置节时只需调用SectionInformation 类的UnprotectSection 方法即可轻松地完成解密,下面对ProtectSection方法和UnprotectSection 方法进行介绍。
(1)ProtectSection 方法
此方法对Web.Config 文件中标记的节以进行加密,语法如下:

public void ProtectSection (string protectionProvider)

参数说明
protectionProvider:要使用的保护提供程序的名称。默认情况下将包含以下保护提供程序加密。
 DPAPIProtectedConfigurationProvider,使用Windows数据保护API(DPAPI)对数据进行加密和解密。
 RSAProtectedConfigurationProvider,使用RSA加密算法对数据进行加密和解密。
 注意:这两个提供程序都提供对数据的强加密;但是,如果打算在多台服务器(如网络场)上使用同一个
加密配置文件,则只有使用RSAProtectedConfigurationProvider 才能导出用于对数据进行加密的加密
密钥,并在另一台服务器上导入它们。
(2)UnprotectSection 方法
此方法从关联的配置节中移除受保护的配置加密,语法如下:

public void UnprotectSection ()


设 计过程


(1)新建一个网站,将其命名为EncryptWebConfig,默认主页为Default.aspx。
(2)在Default 窗体中添加两个Button 控件,分别用来实现加密操作和解密操作。
(3)在“加密”按钮的单击事件中,获取Web.Config 文件中指定的节点,通过SectionInformation 类中的ProtectSection 方法来实现对Web.Config 文件中指定节点加密的操作,代码如下:

protected void btnEncrypt_Click(object sender, EventArgs e)
{
//Configuration对象
Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
//获取配置节点
ConfigurationSection section = config.GetSection("appSettings");
//判断节点是否等于空
if (section != null && !section.SectionInformation.IsProtected)
{
//保护所指定的节点
section.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider");
//保存
config.Save();
RegisterStartupScript("", "<script>alert('加密成功!')</script>");
}
}

在“解密”按钮的单击事件中获取Web.Config文件中指定的节点,通过SectionInformation类中的UnprotectSection方法来实现对Web.Config 文件中指定节点解密的操作,代码如下:

protected void btnDecrypt_Click(object sender, EventArgs e)
{
Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection section = config.GetSection("appSettings");
if (section != null && section.SectionInformation.IsProtected)
{
//移除保护指定的节点
section.SectionInformation.UnprotectSection();
config.Save();
RegisterStartupScript("", "<script>alert('解密成功!')</script>");
}
}


 注意:本实例需要引用System.Web.Configuration 命名空间。

 



0 0