web.config 文件加密

xiaoxiao2023-01-26  92

一般来说,我们是需要对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 相关资源:微信小程序源码-合集3.rar
转载请注明原文地址: https://www.6miu.com/read-4980788.html

最新回复(0)