在web.config或app.config文件里我们经常会存储一些敏感信息,比如connectionStrings或者appSettings,比如像下面的文件。
- <?xml version="1.0"?>
- <configuration>
- <system.web>
- <compilation debug="true" targetFramework="4.0" />
- </system.web>
- <connectionStrings>
- <add name="MyNwConnectionString" connectionString="Server=myServerAddress;Database=myDataBase;User Id=myUsername; Password=myPassword;"/>
- </connectionStrings>
- <appSettings>
- <add key="User" value="myUsername"/>
- <add key="Password" value="myPassword"/>
- </appSettings>
- </configuration>
- using System;
- using System.Configuration;
- namespace WebConfigEncryptTest
- {
- public partial class WebForm1 : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- string user = ConfigurationManager.AppSettings.Get("User");
- string password = ConfigurationManager.AppSettings.Get("Password");
- string connectionString = ConfigurationManager.ConnectionStrings["MyNwConnectionString"].ConnectionString;
- }
- }
- }
(一)加密文件可以使用的Provider
.NET为我们提供了一个工具aspnet_regiis.exe来对web.config文件中的敏感信息进行加密(app.config文件可以先改名为web.config,加密后再改回app.config)。你可以使用两个provider中的一个来进行加密:
- System.Configuration.DPAPIProtectedConfigurationProvider:在System.Configuration.dll中,使用Windows DPAPI(Data Protection API)来进行加密,密钥存在Windows Local Security Authority(LSA)中。注意:当使用DPAPIProtectedConfigurationProvider时,加密文件所使用的帐号需要与运行web application的帐号相同,否则web application无法解密加密的内容。
- System.Configuration.RSAProtectedConfigurationProvider:在System.Configuration.dll中,使用RSA算法来进行加密(RSA算法是非对称加密,参见《http://www.fengfly.com/plus/view-215487-1.html 》),公钥存放在config文件当中,只有加密的计算机有密钥。RSAProtectedConfigurationProvider通常是默认的缺省provider。
本文地址 : http://www.fengfly.com/plus/view-215494-1.html
标签: web.config App.config |