web.config 文件加密

一般来说,我们是需要对web.config文件中的一些敏感信息加密的。通常如下节点会考虑加密,除此之外,很多节点通常都不会被加密,甚至于不能被加密:

1) <appSettings> 一般包含一些我们自定义的信息。
2) <connectionStrings> 这个大家比较熟悉,包含连接数据库用的字符串。
3) <identity> 包含使用impersonate时的账户信息。
4) <sessionState> 包含将session置于process外的连接字符串。

提到加密,我们一般有会想用什么算法加密,怎么样来加密。第一个问题,ASP.NET提供了两种加密方式,DPAPI和RSA。我们可以选择其中一种方式来加密我们的web.config。第二个问题,我们同样也有两种方式,利用aspnet_regiis.exe工具或在程序中用代码加密。

首先,先谈谈使用aspnet_regiis.exe加密的一些命令。先打开Visual Studio的命令行窗口,然后输入 aspnet_regiis /?,我们可以查看关于aspnet_regiis的一些帮助信息。此例中,我们使用DPAPI来加密connectionStrings,website在IIS的sample1虚拟目录中:

aspnet_regiis -pe "connectionStrings" -app "/sample1" -prov "DataProtectionConfigurationProvider"

如果我们的website还没用publish到IIS中,我们可以使用如下命令来加密 - 给出website的绝对路径:

aspnet_regiis -pef "connectionStrings" C:\Projects\sample1 –prov "DataProtectionConfigurationProvider"

这样一个简单的加密就完成了。在获取这些加密信息时,我们可以使用如下代码,它可以自动帮我们解密:

string connStr = ConfigurationManager.ConnectionStrings["test"].ConnectionString;

如果你想将加密的节点改回原来的状态,你可以使用-pd参数:

aspnet_regiis -pd "connectionStrings" -app "/sample1"



同样,我们也可以在程序用进行加密解密。

加密:

// Get the current configuration file.
Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);

// Get the section.
ConfigurationSection appSec = config.GetSection("appSettings");

if (appSec != null && !appSec.SectionInformation.IsProtected)
{
// Protect (encrypt)the section.
appSec.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");

// Save the encrypted section.
appSec.SectionInformation.ForceSave = true;
config.Save();
}

解密:

Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);

ConfigurationSection section = config.GetSection("appSettings");

if (section != null && section.SectionInformation.IsProtected)
{
section.SectionInformation.UnprotectSection();
config.Save();
}


不过有一点要注意,当你将加密后的website移到另一台IIS上时它是不能进行解密的,因为加密的key是放在本地机器的。此时你需要在另一台server上重新使用aspnet_regiis进行加密。

RSA和DPAPI有点不同。DPAPI的key是难以导出的,而RAS的key是容易导出的。这表明我们可以在本地使用RSA进行加密,然后把这个key导出,并安装到server上就可以直接进行解密了。

转自:http://www.cnblogs.com/David-Qian/archive/2009/01/23/1380355.html
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值