閱讀目錄
一:我們為什么要對web.config配置文件中的配置節加密?
二:怎么樣加密和解密?
三:實例
四:運行效果
一:我們為什么要對web.config配置文件中的配置節加密?
因為在我們的項目中,有的配置節可能包含敏感信息,我們看下面的<connectionStrings/>配置節中包含了我們連接 數據庫的用戶名和密碼以及IP地址,這要是暴露出去是很危險的,還有<identity/>配置節中包含了運行時使用的模擬賬號的用戶名和密 碼,這些配置節都包含着敏感信息,我們不希望密碼以明文的方式存儲在配置文件里,所以我們要對其進行加密
<connectionStrings>
<add name="LocalHostEPGConnectionStr" connectionString="server=.;database=NewNewEPG;User ID=sa;password=123" providerName="System.Data.SqlClient"/>
</connectionStrings>
二:怎么樣加密和解密?
使用SectionIntomation對象可以對web.config進行加密和解密
如果要加密一個配置節,只需要調用SectionIntomation對象的ProtectSection()方法,傳遞一個要使用的提供程序的名字來執行加密
如果要解密一個配置節,當需要解密文件的配置節時,只需要調用SectionIntomation對象的UnprotectSection()方法完成解密
1:ProtectSection()方法
此方法對web.config中的配置節進行加密
語法如下:
public void ProtectSection(string ProtectProvider)
參數說明如下:
ProtectProvider:要使用的保護提供程序的名稱,默認下包含以下保護提供程序加密,這個參數必須寫已 存在的保護提供程序的名稱,比如:“RSAProtectedConfigurationProvider”,不能寫“MyName”,否則會報找不到保 護提供程序“MyName”
1.1:RSAProtectedConfigurationProvider:使用RSA加密算法對數據進行加密和解密
1.2:DPAPIProtectedConfigurationProvider:使用Windows數據保護API(DPAPI)對數據進行加密和解密
2:UnprotectSection()方法
此方法對關聯的配置節移除受保護的配置解密
三:實例
ConfigurationManager來自命名空間System.Configuration,而 WebConfigurationManager來自命名空間System.Web.Configuration,微軟建議:在Web應用程序配置文件的 操作時建議采用WebConfigurationManager ;在客戶端配置文件的操作時建議采用ConfigurationManager ,我們都得引用這兩個命名空間
我們最后看到解密后的<connectionStrings/>配置節和未加密前的配置節是一模一樣的
WebConfigEncryptDecrypt.aspx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Configuration;
using System.Configuration;
namespace EPG.WebAdmin.EncryptDecrypt
{
public partial class WebConfigEncryptDecrypt : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
/// <summary>
/// 加密Web.config文件
/// </summary>
protected void btnEncrypt_Click(object sender, EventArgs e)
{
//得到當前配置文件
Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
//得到節部分
ConfigurationSection section = config.GetSection("connectionStrings");
//如果節不為空並且這個節沒被保護
if (section != null && !section.SectionInformation.IsProtected)
{
//保護指定的節使用RSA加密算法對數據進行加密和解密
section.SectionInformation.ProtectSection("RSAProtectedConfigurationProvider");
//保存
config.Save();
RegisterStartupScript("","<script>alert('加密成功!')</script>");
}
}
/// <summary>
/// 解密Web.config文件
/// </summary>
protected void btnDecrypt_Click(object sender, EventArgs e)
{
//得到當前配置文件
Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
//得到節部分
ConfigurationSection section = config.GetSection("connectionStrings");
//如果節不為空並且這個節被保護
if (section != null && section.SectionInformation.IsProtected)
{
//保護指定的節使用RSA加密算法對數據進行加密和解密
section.SectionInformation.UnprotectSection();
//保存
config.Save();
RegisterStartupScript("", "<script>alert('解密成功!')</script>");
}
}
}
}
四:運行效果
界面設計
未加密的<connectionStrings/>配置節
加密后的<connectionStrings/>配置節
解密后的<connectionStrings/>配置節