使用asp.net2.0或3.5编程加密、解密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。
     打开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>   
     然后在页面中添加两个按钮。命名为:btnEncrypt 和 btnDecrypt. 我们将使用这两个按钮来加密、解密web.config中sections。为两个按钮添加以下button click事件代码: 
C#
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) { } }

你可能感兴趣的:(编程,加密,exception,object,解密,asp.net)