web.config加密与解密

      在Asp.net中的Web.config文件里面,有些隐私信息是我们不愿意被发现的,比如密码、数据库链接等,ASP.NET Configuration API 提供了加密、解密web.config中的配置片段(sections)支持。这为您保护隐私信息(如密码)提供了极大的便利。这篇文章中,我们将讨论如何加密、解密web.config中的sections。
    有两种方法加密配置片段(sections),微软提供了两个providers:DPAPI(Windows Data Protection API)及RSA provider。其中RAS provider为默认。它使用RSA密钥,并拥有公钥和私钥。而DPAPI provider 则使用机器编译内规范密钥(built-in machine-specific key)。下面让我们使用RSA方法加密配置文件中的sections。

1: 打开 Visual Studio > 文件 > 网站> 选择语言(C# or Visual Basic) 及位置创建新的asp.net网站。
2: 然后为项目增加web.config 文件。右击项目>增加新项>WEB配置文件。
    打开web.config文件,在<configuration>标记中增加以下所示行:

< configuration >
      
< appSettings >
            
< add key = " var1 "  value = " SomeValue " />
      
</ appSettings >
      
< connectionStrings >
< add name = " MyConnString "  connectionString = " Data Source=(local);Initial Catalog=Northwind;Integrated Security=True; "   />
</ connectionStrings >
      
< system.web > ...
</ configuration >

3: 然后在页面中添加两个按钮。命名为:btnEncrypt 和 btnDecrypt. 我们将使用这两个按钮来加密、解密web.config中sections。为两个按钮添加以下button click事件代码:

using  System.Data;
using  System.Configuration;
using  System.Data.SqlClient;
using  System.Web.Configuration;

        
string  provider  =   " RSAProtectedConfigurationProvider " ;
        
string  section  =   " connectionStrings " ;
        
protected   void  btnEncrypt_Click( object  sender, EventArgs e)
        {
            
try
            {
                Configuration confg 
=  WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
                ConfigurationSection confStrSect 
=  confg.GetSection(section);
                
if  (confStrSect  !=   null )
                {
                    confStrSect.SectionInformation.ProtectSection(provider);
                    confg.Save();
                }
                
//  the encrypted section is automatically decrypted!!
                Response.Write( " Configuration Section  "   +   " <b> "   +
                    WebConfigurationManager.ConnectionStrings[
" MyConnString " ].ConnectionString  +   " </b> "   +   "  is automatically decrypted " );
            }
            
catch  (Exception ex)
            {
            }
        }
        
protected   void  btnDecrypt_Click( object  sender, EventArgs e)
        {
            
try
            {
                Configuration confg 
=  WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
                ConfigurationSection confStrSect 
=  confg.GetSection(section);
                
if  (confStrSect  !=   null   &&  confStrSect.SectionInformation.IsProtected)
                {
                    confStrSect.SectionInformation.UnprotectSection();
                    confg.Save();
                }
            }
            
catch  (Exception ex)
            {
            }
        }

    在上面的代码中,我们使用指定的虚拟路径打开web.config文件,并将其转化为 System.Configuration.Configuration 对象。然后调用方法 GetSection()得到指定的ConfigurationSection对象,这里是connectionStrings。 ConfigurationSection.SectionInformation 属性为我们提供SectionInformation 对象, 最后为SectionInformation 对象调用方法: ProtectSection() 实现sections的加密.
    同样,解密section时,只需要在SectionInformation 对象上调用UnprotectSection() 方法。

 

    4: 下面我们在应用程序中回击加密按钮,然后关闭应用程序,打开web.config文件,你将看到<connectionString>部分已经被加密成以下的样子 :

< 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 > ZehN7B + VXBdJTe1X3NFz9Uz3NqxvjSMmbytLeHGNlZa4
JkkpRkXzphm5sedHeMTk5KZCHxoYrJ4ssJ0OcZnzLxNUrAB9Ie3y8xJVWJ2s0RQ
dmaGk5bSJADE1xKJBuOtDIOi
/ Ron7qJDWXwllC3v
vmNwgabmJ9RU
+ RN35TOQpznc =</ CipherValue >
     
</ CipherData >
    
</ EncryptedKey >
   
</ KeyInfo >
   
< CipherData >
    
< CipherValue > q2amqNwjeyEbMxF5pZ3XqfboNUJKSml773mPkISGi6uWCWCDPs
0ICClmH1eQYcsI9FlxFvEfyRyRRugqOU2xe
+ gd3aRZEZ5irpGFB45Fn6M + te7kg
OeTK1gjGEsbeaNjBNwgpcXMh9RiA9xVOvWlLAyJ3u8DsDQ
+ 4JmM / zTUtxer / 8Dl
UI7
+ u8D + 9V4b5tWxShp4BToMFdTcefhMb19pGdn + jocGet
WBJirO5CJsLXI
=</ CipherValue >
   
</ CipherData >
</ EncryptedData >
</ connectionStrings >

 

     5: 再次运行程序,并点击“解密”按钮,你将看到 <connectionStrings> 片段(section)已返回加密前的样式,不再是无法阅读的加密字符了。


    提示: 需要指出的是像一些 'section groups' 如 <system.net>, <mailSettings> 等,是不能加密的。只有'sections' 可以加密,除了 极少部分如: <configProtectedData>, <processModel>, <httpRuntime> 等一些被 ASP.NET/ISAPI访问的片段.   使用 aspnet_setreg.exe 命令行工具可以加密这些sections.
    你也可以使用aspnet_regiis.exe 命令行工具加密Web.config文件中的sections
    加密:

aspnet_regiis.exe  - pef  " connectionStrings "   " C:\Inetpub\wwwroot\YourWebSite "  –prov  " RSAProtectedConfigurationProvider "

    解密:

aspnet_regiis.exe  - pdf  " connectionStrings "   " C:\Inetpub\wwwroot\YourWebSite "


      尽管ASP.NET拒绝了所有以.config扩展名的请求,但是当你将程序布置到WEB服务器,此时拥有文件访问权限的人将有机会阅读到这些敏感信息。ASP.NET提供了我们一些易于使用的办法保护配置section,我们应该充分利用这些办法。

 

 

转自:http://pxtfh.blog.163.com/blog/static/12313452009316532501/

 

你可能感兴趣的:(config)