web.config/app.config敏感數據加/解密的二種方法

一 建立虛擬目錄  http://localhost/EncryptWebConfig,並添加web.config,其中包含數據庫連接字符串:

    <connectionStrings>
            <add name="Conn" connectionString="Data Source=liuwu;User ID=liuwu;Password=liuwu;"/>
    </connectionStrings>

二  運行 aspnet_regiis -pe "connectionStrings" -app "/EncryptWebConfig" -prov "DataProtectionConfigurationProvider"

  • aspnet_regiis 位於%WinDir%\Microsoft.NET\Framework\<versionNumber>目錄下。
  • -pe 指定要加密的配置節,這裏是 connectionStrings 。
  • -app 指定該配置文件所在的虛擬目錄,這裏是EncryptWebConfig。
  • -prov 指定要使用的提供程序,這裏使用的是DataProtectionConfigurationProvider。

 

 

一.利用代碼加解密



using System.Web.Configuration;


//加密web.Config中的指定節
private void ProtectSection(string sectionName)
{
Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection section = config.GetSection(sectionName);
if (section != null && !section.SectionInformation.IsProtected)
{
section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
config.Save();
}
}

//解密web.Config中的指定節
private void UnProtectSection(string sectionName)
{
Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection section = config.GetSection(sectionName);
if (section != null && section.SectionInformation.IsProtected)
{
section.SectionInformation.UnprotectSection();
config.Save();
}
}

示例:

//加密連接字符串
protected void btnEncrypt_Click(object sender, EventArgs e)
{
ProtectSection("connectionStrings");
}

變化:

加密前:
<connectionStrings>
<add name="connStr" connectionString="Data Source=server;Initial Catalog=Lib;User ID=sa;password=***"
providerName="System.Data.SqlClient" />
</connectionStrings>


加密後:
<connectionStrings configProtectionProvider="DataProtectionConfigurationProvider">
<EncryptedData>
<CipherData>


<CipherValue>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAYzAtjjJo0km/XdUrGFh3YAQAAAACAAAAAAADZgAAqAAAABAAAAD5H0RB6uSYHCk33lo9x5VHAAAAAASAAACgAAAAEAAAALS6KNeUNySZfZ/0tpmh7YWAAQAA85NFHJH

oVx1aW5pTaFfLtTo5J9lWoBR76IYIinLiIjcTeJ4tuAstgCspZlK9NMgzyWmWbbNbb8Z8canVCUpdKF0xmTBTpVih08TtODLszcUpCsJGvEgxuDPi6JtKjG/nT+UvpRp154TNnm04LP/iq1InDxePW2tEViHIiooEXARX8FLY00R

FBaUgarrfi5Fppu4usqavdnj7oqwFEbp3MXOaWY6m9qyVzNsf2G1UwBrivsrM4hZUcr1hy/S87co63ioWie8QDVgGuaTEaSyklC9STyvRsLU6A/QxalCHY4VoRjzNS/27vGoin+c3AJ587wMKJyJBiV08DyzoGM7elAlg8yTAeHv

VMLOEFcTUwsCG0f2rwhi3fZYUyykczYsfHXLEXdbJ+YRiBxYWP6xzffIdyWzrawxaIfnPq/pw6e2Vrwt6tJthDImu0tzXdwupbJVdy4T5vQvy4Fw3SB9lmbSZQacekaXcViBdX7Tejx7TTpDs36RdAOf8WcVMJH4FFAAAACjQFCa

OcSfbD2LXX4YP506vHDXw</CipherValue>
</CipherData>
</EncryptedData>
</connectionStrings>



注意:
加密後,仍然可以按以前的操作來讀取,不需要額外的解決操作,因爲
<connectionStrings configProtectionProvider="DataProtectionConfigurationProvider">
這裏已經指定了用何種方式解密,asp.net會自動處理



二.利用aspnet_regiis.exe工具加解密

步驟:
1.先在本地生成RSA容器(有關RSA的詳細操作,可參見http://msdn.microsoft.com/zh-cn/library/yxw286t2(VS.80).aspx )
aspnet_regiis.exe -pc "JimmyKeys" -exp
注:JimmyKeys爲容器名字,可隨便改



2.再將RSA導出到xml文件
aspnet_regiis.exe -px "JimmyKeys" "c:\JimmyKeys.xml"



3.在web.config中增加一節,一般放在<appSettings>之前就可以了,如下

<configProtectedData>
<providers>
<add name="JimmyRSAProvider"
type="System.Configuration.RsaProtectedConfigurationProvider,System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
keyContainerName="JimmyKeys"
useMachineContainer="true" />

</providers>
</configProtectedData>

<appSettings>
...

4.將web.config加密
aspnet_regiis.exe -pef "appSettings" "c:\website" -prov "JimmyRSAProvider"

解密:
aspnet_regiis.exe -pdf "appSettings" "c:\website"



5.部署到遠程服務器(1臺或多臺)
a.將網站文件與JimmyKeys.xml(也就是導出的RSA容器文件)先上傳到服務器,同時導入RSA
aspnet_regiis.exe -pi "JimmyKeys" "c:\JimmyKeys.xml"



b.確認服務器上aspx登錄所用的默認帳號
Response.Write(System.Security.Principal.WindowsIdentity.GetCurrent().Name);
隨便建一個aspx,把上一行代碼貼到裏面就可以了,IIS5環境下輸出的是ASPNET,IIS6環境下輸出的是NETWORK SERVICE,IIS7下沒試過也不知道輸出的是啥玩意兒



c.授於RSA窗口的讀取權限給b中的默認帳號
aspnet_regiis.exe -pa "JimmyKeys" "NETWORK SERVICE"


順便把剛纔這些個操作的命令整理成幾個批處理

1.本機bat(新建RSA容器,導出容器,加密web.config)
%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -pz "JimmyKeys"
%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -pc "JimmyKeys" -exp
%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -px "JimmyKeys" "c:\JimmyKeys.xml"
%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -pef "appSettings" "c:\website" -prov "JimmyRSAProvider"


2.遠程服務器bat(導入RSA容器,授權)
%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -pi "JimmyKeys" "c:\JimmyKeys.xml"
%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -pa "JimmyKeys" "NETWORK SERVICE"



加密前:
<connectionStrings>
<add name="connStr" connectionString="Data Source=server;Initial Catalog=Lib;User ID=sa;password=***"
providerName="System.Data.SqlClient" />
</connectionStrings>

加密後:
<connectionStrings configProtectionProvider="JimmyRSAProvider">
<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>breSi2wD4X4CAKh0puzhYtyltmR3cp9JfEE8Yw03NeWGZCOoEvDuxAceKLEsmYx8r/tI5NsZxOmY20pQzD1KvGELzz4rhkEPE9LKTAwyKNhqzMPFoRnjsdGTvs6JhrvVat9rdvgKbfTvVLXuvpXgSeNB0T6XJWq

/vOIU7KTyFjk=</CipherValue>
</CipherData>
</EncryptedKey>
</KeyInfo>
<CipherData>


<CipherValue>c4HD+EfJl//pv4eEzT938aWYhLyPBUt8lbNWf4Y4c6tewWLNBTwgYXtxPh6TnF8ne6s9H5C/AwXy/3JECuNEd8YGOO+RDhxw8NySd8vUc53+iUiHW5TLs/aoIvy8k1yOfLWGKFFWPtoX4F4gMTS+MAmhkiHQ46p

H2VyjyprNsl8LE2pGNjDOJnDeGYq+wkn2iw968+qjuTCibGJn6h6iGYGHYmkYUrgRzfo3iIZu+eCWE2IqCP+s58eQRjU3MxJ2BqeUU9HaKy4=</CipherValue>
</CipherData>
</EncryptedData>
</connectionStrings>

同樣,這種方式加密後,aspx讀取節點時也無需任何解密處理,代碼不用做任何修改


注意:並不是所有的節點都能加密,ASP.NET 2.0僅支持對Web.config的部分配置節進行加密,以下配置節中的數據是不能進行加密的:
• <processModel>
• <runtime>
• <mscorlib>
• <startup>
• <system.runtime.remoting>
• <configProtectedData>
• <satelliteassemblies>
• <cryptographySettings>
• <cryptoNameMapping>
• <cryptoClasses>


另外,除了AppSettings和ConnectionStrings以外的其它節點,可以這樣寫:
aspnet_regiis.exe -pef "system.serviceModel/behaviors" "d:\website\cntvs\"

即對<system.serviceModel>下的<behaviors>節點加密,這一節點同樣適用於代碼方式加密,經過多次嘗試,似乎除了AppSettings和ConnectionStrings以外的其它節點,只能支持二級節點。


象以下寫法:
aspnet_regiis.exe -pef "system.serviceModel/behaviors/endpointBehaviors" "d:\website\cntvs" 
運行時會報錯:

未找到配置節“system.serviceModel/behaviors/endpointBehaviors”。





作者:菩提樹下的楊過
出處:http://yjmyzz.cnblogs.com
本文版權歸作者和博客園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接,否則保留追究法律責任的權利。

 

1. 向項目添加app.config文件:
右擊項目名稱,選擇“添加”→“添加新建項”,在出現的“添加新項”對話框中,選擇“添加應用程序配置文件”;如果項目以前沒有配置文件,則默認的文件名稱爲“app.config”,單擊“確定”。出現在設計器視圖中的app.config文件爲:
<?xmlversion="1.0"encoding="utf-8" ?>
<configuration>
</configuration>
在項目進行編譯後,在bin\Debuge文件下,將出現兩個配置文件(以本項目爲例),一個名爲“JxcManagement.EXE.config”,另一個名爲“JxcManagement.vshost.exe.config”。第一個文件爲項目實際使用的配置文件,在程序運行中所做的更改都將被保存於此;第二個文件爲原代碼“app.config”的同步文件,在程序運行中不會發生更改。
2.  connectionStrings配置節:
請注意:如果您的SQL版本爲2005 Express版,則默認安裝時SQL服務器實例名爲localhost\SQLExpress,須更改以下實例中“Data Source=localhost;”一句爲“Data Source=localhost\SQLExpress;”,在等於號的兩邊不要加上空格。
<!--數據庫連接串-->
     <connectionStrings>
         <clear />
         <addname="conJxcBook"
              connectionString="Data Source=localhost;Initial Catalog=jxcbook;User                                   ID=sa;password=********"
              providerName="System.Data.SqlClient" />
     </connectionStrings>
3. appSettings配置節:
appSettings配置節爲整個程序的配置,如果是對當前用戶的配置,請使用userSettings配置節,其格式與以下配置書寫要求一樣。
<!--進銷存管理系統初始化需要的參數-->
     <appSettings>
         <clear />
         <addkey="userName"value="" />
         <addkey="password"value="" />
         <addkey="Department"value="" />
         <addkey="returnValue"value="" />
         <addkey="pwdPattern"value="" />
         <addkey="userPattern"value="" />
</appSettings>
4.讀取與更新app.config
對於app.config文件的讀寫,參照了網絡文章:http://www.codeproject.com/csharp/ SystemConfiguration.asp標題爲“Read/Write App.Config File with .NET 2.0一文。
請注意:要使用以下的代碼訪問app.config文件,除添加引用System.Configuration外,還必須在項目添加對System.Configuration.dll的引用。
4.1 讀取connectionStrings配置節
///<summary>
///依據連接串名字connectionName返回數據連接字符串
///</summary>
///<param name="connectionName"></param>
///<returns></returns>
private static string GetConnectionStringsConfig(string connectionName)
{
string connectionString =
        ConfigurationManager.ConnectionStrings[connectionName].ConnectionString.ToString();
    Console.WriteLine(connectionString);
    return connectionString;
}
4.2 更新connectionStrings配置節
///<summary>
///更新連接字符串
///</summary>
///<param name="newName">連接字符串名稱</param>
///<param name="newConString">連接字符串內容</param>
///<param name="newProviderName">數據提供程序名稱</param>
private static void UpdateConnectionStringsConfig(string newName,
    string newConString,
    string newProviderName)
{
    bool isModified = false;    //記錄該連接串是否已經存在
    //如果要更改的連接串已經存在
    if (ConfigurationManager.ConnectionStrings[newName] != null)
    {
        isModified = true;
    }
    //新建一個連接字符串實例
    ConnectionStringSettings mySettings =
        new ConnectionStringSettings(newName, newConString, newProviderName);
    // 打開可執行的配置文件*.exe.config
    Configuration config =
        ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    // 如果連接串已存在,首先刪除它
    if (isModified)
    {
        config.ConnectionStrings.ConnectionStrings.Remove(newName);
    }
    // 將新的連接串添加到配置文件中.
    config.ConnectionStrings.ConnectionStrings.Add(mySettings);
    // 保存對配置文件所作的更改
    config.Save(ConfigurationSaveMode.Modified);
    // 強制重新載入配置文件的ConnectionStrings配置節
    ConfigurationManager.RefreshSection("ConnectionStrings");
}
4.3 讀取appStrings配置節
///<summary>
///返回*.exe.config文件中appSettings配置節的value項
///</summary>
///<param name="strKey"></param>
///<returns></returns>
private static string GetAppConfig(string strKey)
{
    foreach (string key in ConfigurationManager.AppSettings)
    {
        if (key == strKey)
        {
            return ConfigurationManager.AppSettings[strKey];
        }
    }
    return null;
}
4.4 更新connectionStrings配置節
///<summary>
///在*.exe.config文件中appSettings配置節增加一對鍵、值對
///</summary>
///<param name="newKey"></param>
///<param name="newValue"></param>
private static void UpdateAppConfig(string newKey, string newValue)
{
    bool isModified = false;   
    foreach (string key in ConfigurationManager.AppSettings)
    {
       if(key==newKey)
        {   
            isModified = true;
        }
    }
 
    // Open App.Config of executable
    Configuration config =
        ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    // You need to remove the old settings object before you can replace it
    if (isModified)
    {
        config.AppSettings.Settings.Remove(newKey);
    }   
    // Add an Application Setting.
    config.AppSettings.Settings.Add(newKey,newValue);  
    // Save the changes in App.config file.
    config.Save(ConfigurationSaveMode.Modified);
    // Force a reload of a changed section.
    ConfigurationManager.RefreshSection("appSettings");
}
5.加密配置文件
此節代碼參照Dariush Tasdighi所著文章《Encrypt and Decrypt of ConnectionString in app.config and/or web.config!》,原文載於http://www.codeproject.com/useritems/Configuration_File.asp
請注意:(1)要使用以下的代碼訪問app.config文件,除添加引用System.Configuration外,還必須在項目添加對System.Configuration.dll的引用; (2)以下示例代碼中的DPAPI提供程序爲“DataProtectionConfigurationProvider”,這是一種基於機器名和當前用戶密碼的加密方式。如果計劃在多臺服務器(Web 場合)上使用相同的加密配置文件,則只有通過 RSAProtectedConfigurationProvider 才能導出加密密鑰,並將其導入其他服務器。(3)加密後的配置文件不需要解密即可用上述方法直接讀取。
5.1 加密connectionStrings配置節
///<summary>
///加密配置文件中的ConnectionString節
///</summary>
///<param name="protect">true爲加密,false爲解密</param>
public static void ConnectionStringProtection( bool protect)
{
    //取得當前程序的執行路徑
    string pathName = Application.ExecutablePath;
    // 定義Dpapi提供程序的名稱.
    string strProvider = "DataProtectionConfigurationProvider";
 
    System.Configuration.Configuration oConfiguration = null;
    System.Configuration.ConnectionStringsSection oSection = null;
 
    try
    {
        // 打開配置文件,並取得connectionStrings配置節.
        oConfiguration =
                System.Configuration.ConfigurationManager.OpenExeConfiguration(pathName);
 
        if (oConfiguration != null)
        {
            bool blnChanged = false;
            oSection = oConfiguration.GetSection("connectionStrings") as
                System.Configuration.ConnectionStringsSection;
 
            if (oSection != null)
            {
                if ((!(oSection.ElementInformation.IsLocked)) && (!(oSection.SectionInformation.IsLocked)))
                {
                    if (protect)
                    {
                        if (!(oSection.SectionInformation.IsProtected))
                        {
                            blnChanged = true;
                            // 加密connectionStrings配置節.
                    oSection.SectionInformation.ProtectSection(strProvider);
                        }
                    }
                    else
                    {
                        if (oSection.SectionInformation.IsProtected)
                        {
                            blnChanged = true;
                            // 解密connectionStrings配置節.
                            oSection.SectionInformation.UnprotectSection();
                        }
                    }
                }
 
                if (blnChanged)
                {
                    // 如果connectionStrings配置節被更改,則強制保存它.
                    oSection.SectionInformation.ForceSave = true;
                    // 保存對connectionStrings配置節的更改.
                    oConfiguration.Save();
                }
            }
        }
    }
    catch (System.Exception ex)
    {
        throw (ex);
    }
    finally
    {
    }
}
5.2 加密appSettings配置節
///<summary>
///加密配置文件中的AppSettings配置節
///</summary>
///<param name="protect">true爲加密,false爲解密</param>
public static void AppSettingProtection(bool protect)
{
    //取得當前程序的執行路徑
    string pathName = Application.ExecutablePath;
    // Define the Dpapi provider name.
    string strProvider = "DataProtectionConfigurationProvider";
 
    System.Configuration.Configuration oConfiguration = null;
    System.Configuration.AppSettingsSection oSection = null;
 
    try
    {
        // Open the configuration file and retrieve the connectionStrings section.
        oConfiguration =
            System.Configuration.ConfigurationManager.OpenExeConfiguration(pathName);
 
        if (oConfiguration != null)
        {
            bool blnChanged = false;
            oSection = oConfiguration.GetSection("appSettings") as
                System.Configuration.AppSettingsSection;
 
            if (oSection != null)
            {
                if ((!(oSection.ElementInformation.IsLocked)) &&
                     (!(oSection.SectionInformation.IsLocked)))
                {
                    if (protect)
                    {
                        if (!(oSection.SectionInformation.IsProtected))
                        {
                            blnChanged = true;
                            // Encrypt the section.
                            oSection.SectionInformation.ProtectSection(strProvider);
                        }
                    }
                    else
                    {
                        if (oSection.SectionInformation.IsProtected)
                        {
                            blnChanged = true;
                            // Remove encryption.
                            oSection.SectionInformation.UnprotectSection();
                        }
                    }
                }
 
                if (blnChanged)
                {
                    // Indicates whether the associated configuration section will be saved even   
                    // if it has not been modified.
                    oSection.SectionInformation.ForceSave = true;
                    // Save the current configuration.
                    oConfiguration.Save();
                }
            }
        }
    }
    catch (System.Exception ex)
    {
        throw (ex);
    }
    finally
    {
    }
}

 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章