文章出處

介紹

這篇文章我將介紹如何利用ASP.NET來加密和解密Web.config中連接字符串

背景描述

在以前的博客中,我寫了許多關于介紹 Asp.net, Gridview, SQL Server, Ajax, JavaScript等的文章。大多數情況下,我都把數據庫的連接字符串放在了web.config中。其中包含許多敏感信息,包括連接數據庫的用戶名密碼等。然而我們在web.config和machine.config中以純文本的方式保存密碼安全嗎?

如果我們的程序只是部署在內部服務器中,這應該沒什么問題。但如果我們的程序是運行在共享主機上面,那我們應該提高安全等級了。ASP. NET 2.0提供了一個保護配置模型來加密和解密web.config中sections信息。RSAProtectedConfigurationProvider:默認通過RSA公鑰來加密和解密。

通過在命令行中工具運行aspnet_regiis.exe命令,可以對web.config中的連接串進行加密和解密。

第一種方式

首先,我們通過在windows命令行中執行aspnet_regiis.exe來加密與解密。

在VS中創建一個新的websit項目,打開web.config,加入數據庫連接串,如:

然后我們按下面的步驟來加密和解密數據連接串

 <connectionStrings>
    <add name="dbconnection" connectionString="Data Source=RahulMittal;Integrated Security=true;Initial Catalog=MySampleDB"/>
  </connectionStrings >

1. 開始菜單>>所有程序>>Microsoft visual studio 2008 >> Visual Studio Tools >> Visual Studio 2008 開發人員命令提示(如果是windows7,點右鍵與管理員身份運行)

2. 在命令窗口中,輸入命令 aspnet_regiis.exe -pef "connectionStrings" "C:\VisualStudio2008\Authorization"

 –pef表明程序是以文件系統的形式建立的。第二個“connectionStrings”是你要加密的configuration 節點名字。第三個參數指名 web.config的物理路徑。

3. 成功執行命令后會顯示:加密成功。

現在,再打開程序中的 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>ZNUbIEnOwlZzC8qbzHj5F2GS9gLYSkWCIgCJGkrgZAX8A+8oEIssyohhxUKvAubD3jizFc5IjbLGt7HNXhoFhXNTUPYz2y6tdKJDVgDmtCgVf8Z2C990zoMRBJG+VXhmgnlo1vtHYhGx8x/bBzE1prT1+xDpep98vHF22d+LrVI=</CipherValue>
          </CipherData>
        </EncryptedKey>
      </KeyInfo>
      <CipherData>
        <CipherValue>tODWlPD0Q/B/mP14GQ/5tUxcjmhHcy9a0oPunV5osNrMQRztgi2h5V6sxJOEh+NC+G9gQNkv1huXf1s7eoZRRLy5/LDtLXzzqMUOqLSlJUs9igChvi33c9XG4rwGF15Tpn4N34bpQBt94n0rpSkQ18V9HCPzii+UO64PlA+ykDeQhc9aQr4gO3mCfUzmY2S9gsXzRbzdq0oCWBDvx8UkX2uDxaysVHC9Fo7u6IrlpU0+hOdK95Y3/A==</CipherValue>
      </CipherData>
    </EncryptedData>
  </connectionStrings>

我們在程序中并不要寫任何代碼來解密連接字符串,因為.NET會自動的為我們解密。如果我們要用連接字符串,可以像平常那樣調用.

string strconnection = ConfigurationManager.AppSettings["dbconnection"].ToString();

如果我們想解密,只需要在VS的命令窗口中,輸入aspnet_regiis.exe -pdf "connectionStrings" "C:\VisualStudio2008\Authorization"
成功執行后,會顯示解密成功。
再打開web.config,我們可以看到解密后的字符串。

現在,我們知道了如何在文件系統中加密和解密連接字符串。如果我們想加密運行在IIS上的默認網站,就像IE上展示的那樣,可以用下面的命令。

加密IIS默認網站的web.config

aspnet_regiis.exe -pe "connectionStrings" -app "/SampleWebSite"

-pe說明程序是運行在IIS上的。第二個參數指名要加密的configuration節點。-app用來指定虛擬目錄,最后一個參數就是程序部署的虛擬目錄名。

 Decrypt connectionStrings in web.config of IIS based site

解密IIS默認網站上的web.config

aspnet_regiis.exe -pd "connectionStrings" -app "/SampleWebSite"

到這里我們知道如何用命令行工具執行aspnet_regiis.exe命令來加密和解密web.config了。下面我將介紹如何在后臺代碼中來加密解密web.config。

第二種方式

在第二種方法中我會用RSAProtectedConfigurationProvider和DataProtectionConfgurationProvider來加密解密web.config

首先,打開Default.aspx,添加如下代碼:

<html xmlns="http://www.w3.org/1999/xhtml">
    <head  runat="server">
      <title>Untitled Page</title>
    </head>
    <body>
      <form id="form1"  runat="server">
        <div>
          <asp:Button id="btnEncrypt" runat="server" Text="Encrypt" onclick="btnEncrypt_Click" />
          <asp:Button ID="btnDecrypt" runat="server" Text="Decrypt" onclick="btnDecrypt_Click" />
        </div>
      </form>
    </body>
  </html>

打開后臺代碼,添加下列命名空間:

using System;
using System.Configuration;
using System.Web.Configuration;

再添加如下代碼

string provider = "RSAProtectedConfigurationProvider";
string section = "connectionStrings";
protected void Page_Load(object sender, EventArgs e)
{
 
}
protected void btnEncrypt_Click(object sender, EventArgs e)
{
   Configuration confg = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
   ConfigurationSection configSect = confg.GetSection(section);
   if (configSect != null)
   {
      configSect.SectionInformation.ProtectSection(provider);
      confg.Save();
   }
}
 
protected void btnDecrypt_Click(object sender, EventArgs e)
{
   Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
   ConfigurationSection configSect = config.GetSection(section);
   if (configSect.SectionInformation.IsProtected)
   {
      configSect.SectionInformation.UnprotectSection();
      config.Save();
   }
}

完成之后,打開web.config,添加數據庫連接字符串

 <connectionStrings>
    <add name="dbconnection" connectionString="Data Source=RahulMittal;Integrated Security=true;Initial Catalog=MySampleDB"/>
  </connectionStrings >

現在運行程序并點擊加密按鈕之后,再打開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>WagJ9DDjWTNc1nmYVNQXaQqXalQzXaiCHAOtUJvTWBRZiuT6UK1fBElM80PnL6dC5Umb8qvfHdkSMgoMW9CJzwOTZ0zTy17JBGZqRQmlfW2G9LacoWIil0UrxjhgmJmRXhwXHFpdGwEVl7AoQGVlJGabXuChutaTxmfGOoUbCr0=</CipherValue>
          </CipherData>
        </EncryptedKey>
      </KeyInfo>
      <CipherData>
        <CipherValue>qry5qnr3qxOgyoNPeP7OKEiHpr/PPTsaeQ2mYUsSK7cg4Kkl9uPO4RyUXgBIkgCTsjbObqLlyndcSBnYyek6bxG/IBL82G1R5J1ci8i1eyt8kIDqouzYOx5vtouErld4z1L+7WGf9Wg37QAH5RiiEfkCHndJJq3dTqjxnnXZSno6NgbxSXDfqzwE/eKDVhGV3oaTQSfjVmO8e5a9wvREYeeyasDhojx8J2mdy7/Q9rEIpv98RTiRxA==</CipherValue>
      </CipherData>
    </EncryptedData>
  </connectionStrings>

如果我們想用DataProtectionConfigurationProvider來實現加密與解密,只需在代碼中將RSAProtectedConfigurationProvider替換成DataProtectionConfigurationProvider即可。

 

原文:http://www.codeproject.com/Tips/304638/Encrypt-or-Decrypt-Connection-Strings-in-web-confi


文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()