加密(Asp.Net配置檔案的)配置節

一劍平江湖發表於2014-05-03

序言
開發者經常需要在配置檔案中儲存一些配置資訊。比如,資料庫聯接字串,使用者名稱和密碼等。(這就提出)一個要求,使用ASP.NET 1.x的時候,.net framework應該提供一些方法密或解密這些資訊。慶幸的是,ASP.NET 2.0可以靈活的滿足這一要求。這篇文章將會展示怎樣用嵌入的工具和程式碼保護一個特定的配置節。


怎樣加密配置檔案?
ASP.NET 2.0允許你加密配置檔案的一部分,來確保他們的安全(相對的)。這個特徵通常被叫做受保護配置(Protected Configuration)。ASP.NET提供了兩種方法來加密和解密配置檔案


在命令提示行中,通過ASPNET_REGIIS.EXE工具 
通過 configuration management 類 
加密與解密通過兩個受保護的提供者實現


RsaProtectedConfigurationProvider 
DataProtectionConfigurationProvider 
儲存在可以在你的機器裡的machine.config檔案中找到這兩個提供者。RsaProtectedConfigurationProvider是預設的提供者。下面的部分是machine.config中的相關標記


<configProtectedData
defaultProvider="RsaProtectedConfigurationProvider">
<providers>
<add name="RsaProtectedConfigurationProvider"
type="System.Configuration.RsaProtectedConfigurationProvider,
System.Configuration, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a"
description="Uses RsaCryptoServiceProvider to encrypt and decrypt"
keyContainerName="NetFrameworkConfigurationKey"
cspProviderName="" useMachineContainer="true" useOAEP="false" />
<add name="DataProtectionConfigurationProvider"
type="System.Configuration.DpapiProtectedConfigurationProvider,
System.Configuration, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a"
description="Uses CryptProtectData and CryptUnProtectData
Windows APIs to encrypt and decrypt" useMachineProtection="true"
keyEntropy="" />
</providers>
</configProtectedData>
使用ASPNET_REGIIS.EXE加密一個配置節
讓我們來看看如何使用ASPNET_REGIIS.EXE工具來加密<connectionStrings>配置節。


用VS.Net建立一個網站叫做EncryptTest,加入一個web.config檔案。然後加入如下的<connectionStrings>配置節:




<connectionStrings>
<add name="connstr" connectionString=
"data source=.\sqlexpress;initial catalog=
northwind;integrated security=true" />
</connectionStrings>
我們簡單的加入了一個聯接字串,指向了Northwind資料庫。然後開啟default.aspx檔案,拖拽一個GridView控制元件,並在Page_Load中輸入如下程式碼:




protected void Page_Load(object sender, EventArgs e)
{
string strConn = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;
SqlDataAdapter da = new SqlDataAdapter("select * from customers", strConn);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();

這段程式碼裡,我們用ConfigurationManager類從<connectionStrings>配置節讀取了聯接字串。這裡用們有意的用了手動的方法代替了SqlDataSource空間,就是為了證明內建的類ConfigurationManager自動的機密了加密版本的聯機字串。


 現在開啟Visual Studio 2005命令提示,執行下面的命令:
aspnet_regiis -pe "connectionStrings" -app "/encrypttest"
-pe開關用來指定web.config中需要加密的節(我們的例子裡是connectionStrings)。
-app開關用來指定IIS裡面的虛擬路徑


執行以後,如果你再檢視一下web.config檔案,你會看到這樣的情形:


<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>NW4gFUtlA3XkbKu42FQ3kYV8EKmwzy9r53vrI2rjV
ZFqjsr00/MwS6TWqjnsguN09kWvNIrbfWu5+Gi+DLFhYnGm2NcuaCy
Vic8f5e0Q8u3E7zk2MegZmiri5bSELE1fZneWz4oFb+MHqA94ZO3Be
XBlocou6ydtmJPXZCqLsDQ=</CipherValue>
</CipherData>
</EncryptedKey>
</KeyInfo>
<CipherData>
<CipherValue>T2fswq6Rt7g7VSNUnoe4kNFGSluWCBReQf3DRbXao/
sWaWs4mrJAI6Xy0zNDHY5pKXUUF9Kep2wG84rMVx0QtLIUjBaUKCnrm
Eb+53oYNPjN4Kf5zcPyWoaWwcus4LnJYNtg3oGJUvavZ0tjGXH9+5gB
w/xMrtfDcYAIom9l/IMcO92BKrvimjn/k4Mr8VXxGpvdMkAC3+e6dtW
JeUgQGpepO+RNpWymB5kWj38LjMQ=</CipherValue>
</CipherData>
</EncryptedData>
</connectionStrings>
這個工具已經用RsaProtectedConfigurationProvider(預設的提供者)加密了connectionStrings節點,並且將加密過的標籤返回給配置檔案。你還可以指定具體的Protected Configuration Provider(加密保護配置提供者),使用-prov開關來指定。很簡單,不是麼?
現在,瀏覽你的web頁面。這個web頁面將會在GridView標記里正確的顯示Customers表的內容,這說明ConfigurationManager類在讀取連線字串的時候自動解密了其中的資訊。


使用ASPNET_REGIIS.EXE解密配置節
如果你需要在開發過程中對連線串進行些改動要怎麼辦?不用擔心,ASPNET_REGIIS.EXE工具同樣支援解密節點,僅僅需要執行下面的命令就會恢復到你原來的未加密的版本。aspnet_regiis -pd "connectionStrings" -app "/encrypttest"唯一的區別就是,我們用-pd開關代替了-pa開關。


Encryption and decrypting via code
The task of encrypting and decrypting web.config can also be achieved via code. Let's see how.
Add a new web form to the same web site and design it as shown below:
通過程式碼加密與解密 加密與解密web.config功能同樣可以通過程式碼來完成。讓我們看看怎樣完成的。在同樣的站點下加入一個新的web頁面,並且設計成下面的樣子


在"Encrypt Connection String"按鈕的Click事件中加入如下程式碼:
protected void Button1_Click(object sender, EventArgs e)
{
Configuration config = WebConfigurationManager.
OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection section = config.ConnectionStrings;
if (!section.SectionInformation.IsProtected)
{
section.SectionInformation.ProtectSection
("RsaProtectedConfigurationProvider");
section.SectionInformation.ForceSave = true;
config.Save(ConfigurationSaveMode.Modified);
}
}
 
如果你不是很熟需怎樣修改web.config的內容,下面的這篇文章應該對你有幫助
通過程式修改Web.config檔案的內容。




這段程式碼的上半部分是開啟並修改web.config檔案。然後找到ConnectionStrings配置節。然後,粗體字的部分是非常重要的。ProtectSection()方法指定了你用來加密節點的Protected Configuration Provider(保護配置供應者),然後用這個供應者加密了下一行的節點。程式碼最後將結果儲存。
解密配置節的工作和加密類似:
protected void Button2_Click(object sender, EventArgs e)
{
Configuration config = WebConfigurationManager.
OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection section = config.ConnectionStrings;
if (section.SectionInformation.IsProtected)
{
section.SectionInformation.UnprotectSection();
section.SectionInformation.ForceSave = true;
config.Save(ConfigurationSaveMode.Modified);
}
}
這裡我們用UnprotectSection()方法回覆到未加密的版本。


概述The encryption and decryption can be done in two ways - using ASPNET_REGIIS command line tool or programmatically.ASP.NET 2.0讓保護你的web.config檔案變得非常容易,它允許你通過加密的方式進行保護。無論是加密還是解密都有兩種辦法--使用ASPNET_REGIIS命令列工具 或 程式控制。

相關文章