<?xml version="1.0"?> <configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0"> <connectionStrings configProtectionProvider="DataProtectionConfigurationProvider"> <EncryptedData> <CipherData> <CipherValue>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAed...GicAlQ==</CipherValue> </CipherData> </EncryptedData> </connectionStrings> <system.web> <compilation debug="true"/> <authentication mode="Forms" /> </system.web> |
另外,存在一些你不能使用这个技术加密的配置部分:
· <processModel>
· <runtime>
· <mscorlib>
· <startup>
· <system.runtime.remoting>
· <configProtectedData>
· <satelliteassemblies>
· <cryptographySettings>
· <cryptoNameMapping>
· <cryptoClasses>
为了加密这些配置部分,你必须加密这些值并把它存储在注册表中。存在一个aspnet_setreg.exe命令行工具可以帮助你实现这一过程;我们将在本文后面讨论这个工具。
【提示】Web.Config和Machine.Config之区别:
Web.config文件指定针对一个特定的web应用程序的配置设置,并且位于应用程序的根目录下;而machine.config文件指定所有的位于该web服务器上的站点的配置设置,并且位于$WINDOWSDIR$\Microsoft.Net\Framework\Version\CONFIG目录下。
四、加密选项 开发人员可以使用ASP.NET 2.0提供程序模型来保护配置节信息,这允许任何实现都可以被无缝地插入到该API中。.NET框架2.0中提供了两个内置的提供程序用于保护配置节信息:
· Windows数据保护API(DPAPI)提供程序(DataProtectionConfigurationProvider):这个提供程序使用Windows内置的密码学技术来加解密配置节。默认情况下,这个提供程序使用本机的密钥。你还能够使用用户密钥,但是这要求进行一点定制。
· RSA保护的配置提供程序(RSAProtectedConfigurationProvider):使用RSA公钥加密来加解密配置节。使用这个提供程序,你需要创建存储用于加解密配置信息的公钥和私钥的密钥容器。你能够在一个多服务器场所下使用RSA,这只要创建可输出的密钥容器即可。
当然,如果需要的话,你还能够创建自己的保护设置提供程序。
在本文中,我们仅讨论使用DPAPI提供程序使用机器级密钥。到目前为止,这是最简单的方法,因为它不请求创建任何密钥或密钥容器。当然,其消极的一面在于:一个加密的配置文件仅能够用于首先实现加密的web服务器上;而且,使用机器密钥将允许加密的文本能够被web服务器上的任何
网站所解密。
五、以编程方式加密配置部分 System.Configuration.SectionInformation类对一个配置节的描述进行了抽象。为了加密一个配置节,只需要简单地使用SectionInformation类的ProtectSection(提供程序)方法,传递你想使用的提供程序的名字来执行加密。为了存取你的应用程序的Web.config文件中的一个特定的配置节,你可以使用WebConfigurationManager类(在System.Web.Configuration命名空间中)来引用你的Web.config文件,然后使用它的GetSection(sectionName)方法返回一个ConfigurationSection实例。最后,你可以经由ConfigurationSection实例的SectionInformation属性得到一个SectionInformation对象。
下面,我们通过一个简单的代码示例来说明问题:
privatevoid ProtectSection(string sectionName, string provider) { Configuration config = WebConfigurationManager. OpenWebConfiguration(Request.ApplicationPath); ConfigurationSection section = config.GetSection(sectionName); if (section != null &&!section.SectionInformation.IsProtected) { section.SectionInformation.ProtectSection(provider); config.Save(); } } private void UnProtectSection(string sectionName) { Configuration config =WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath); ConfigurationSection section = config.GetSectio n(sectionName); if (section != null && section.SectionInformation.IsProtected) { section.SectionInformation.UnprotectSection(); config.Save(); } |
你可以从一个ASP.NET页面中调用这个ProtectSection(sectionName,provider)方法,其相应的参数是一个节名(如connectionStrings)和一个提供程序(如DataProtectionConfigurationProvider),并且它打开Web.config文件,引用该节,调用SectionInformation对象的ProtectSection(provider)方法,最后保存配置变化。

发表评论