C# 對 App.config的appSettings節點數據進行加密


.NET平台下的Winform和Asp.net的配置文件默認都是明文保存的,本文使用的是.Net自身如何加密配置文件,不包含自定義的加密規則
但.Net是提供了直接對配置文件加密的功能的,使用.Net加密的配置節在讀取時不需要手動解密,.Net會自行解密並返回解密后的數據。
加密后的數據會保存到一個單獨的配置節點里(不管加密的節點下有多少子項,加密后的數據都在CipherValue 里)
.Net是按照節點來進行加密的,所以如果給像appSettings這樣的節點加密,那么該節點下面的所有數據都會加密(單獨的Key進行加密可以自己Code實現,不太清楚.Net本身是否能只加密節點下某N個Key)
加密后的數據及節點:
<EncryptedData>
    <CipherData>
        <CipherValue>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAABbLHX[...]</CipherValue>
    </CipherData>
</EncryptedData>    

 

加密方法

方法一(利用代碼實現)

        /// <summary>
        /// 對appSettings節點添加健值
        /// 如果健已經存在則更改值
        /// 添加后重新保存並刷新該節點
        /// </summary>
        /// <param name="dict">添加的健值集合</param>
        /// <param name="isProtected">是否加密appSettings節點數據,如果為TrueappSettings節點下所有數據都會被加密</param>
        public static void AddConfig(System.Collections.Generic.Dictionary<string, string> dict, bool isProtected)
        {
            if (dict == null || dict.Count <= 0) return;
            System.Configuration.Configuration configuration =System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            //循環添加或更改健值
            foreach (System.Collections.Generic.KeyValuePair<string, string> key_value in dict)
            {
                if (string.IsNullOrEmpty(key_value.Key)) continue;
                if ( configuration.AppSettings.Settings[key_value.Key]!=null)
                    configuration.AppSettings.Settings[key_value.Key].Value = key_value.Value;
                else
                    configuration.AppSettings.Settings.Add(key_value.Key, key_value.Value);
            }
           
            //保存配置文件
            try
            {
                //加密配置信息
                if (isProtected && !configuration.AppSettings.SectionInformation.IsProtected)
                {
                    configuration.AppSettings.SectionInformation.ForceSave = true;
                    configuration.AppSettings.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
                }
                configuration.Save();
            }
            catch (Exception)
            {
                throw;
            }
            ConfigurationManager.RefreshSection("appSettings");   
           }
        }

 

方法二

利用現成的工具ASP.NET IIS 注冊工具 (Aspnet_regiis.exe),可是它只能針對ASP.NET的Web.config文件,難道我們就沒有辦法了嗎?答案當然是否定的。

配置選項

-pdf section webApplicationDirectory 對指定物理(非虛擬)目錄中的 Web.config 文件的指定配置節進行解密。
-pef section webApplicationDirectory 對指定物理(非虛擬)目錄中的 Web.config 文件的指定配置節進行加密。

 -pdf 和-pef 參數是對指定的物理目錄里的Web.config文件進行加密,我們可以先將App.config文件改名為Web.config,通過這兩個參數便可以“騙”過系統,讓它將指定的配置節進行加密,我們只需要將加密后的文件名改回App.config即可,我們來實驗一下:

第一步:先將目錄下的App.config改名為Web.config。

第二步:打開SDK命令提示,輸入命令:aspnet_regiis -pef "配置節" "目錄",以我的項目為例,加密前的config文件內容如下:

<?xml version="1.0" encoding="utf-8"?>
 <configuration>
   <configSections>
     <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null" />
   </configSections>
   <dataConfiguration defaultDatabase="Connection String" />
   <connectionStrings>
     <add name="Connection String" connectionString="Database=LocomotiveStat;Server=10.167.61.49;User ID=sa;Password=sa;"
       providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>

輸入命令:aspnet_regiis -pef "connectionStrings" "E:\開發目錄",加密后的config文件內容如下:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null" />
  </configSections>
  <dataConfiguration defaultDatabase="Connection String" />
  <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>g2QFQqbHU1L6WUPYqjADqFAvHcdq/7dqCd1U9GlQFEi/nHDVHjqsWvjNywOZtQQg7Q/yW7g8xlRCo0h2+yYd/tQTNoVMu/RKdJmSjZMnmnwpWq+S2VEWK4U106JQwLCfBR/bAF4DHvG47B9KB0JbRfXBt5V2wJVaAI9u3kzuj50=</CipherValue>
          </CipherData>
        </EncryptedKey>
      </KeyInfo>
      <CipherData>
        <CipherValue>blwV/ZW1izFZL80YL5RkcjrIjWkQ0L1gJhgZbxEzzTgOcT24ihrAnv3/rDCG+WIZ7TL5D/rMm7dQwkIsij1Sh3befg6F3+pxcW4oe1w/bovIKuzjs3tokUpBvTTj+fsCs2W/MWUhQaWMKQWkHfS2Ajt6gL6MTYtb3pfQUp0pdHbeRxoqdiAksQ1Zzsi1FtRTi7gTT7hnpF0pJs+W9mxTVDMO/qSZXfXLOEMIs/A5ExcfvR5GjpaPuDeLuSsCN3XtjaiXzaDQ3It7j+r66+L2C0xvEhbT9SsG</CipherValue>
      </CipherData>
    </EncryptedData>
  </connectionStrings>
</configuration>

   由此可見,我們已經完成了任務,現在只需要將Web.config文件名改回App.config即可,在應用程序項目中無需對該文件進行解密操作,.NET框架會自動替我們完成,如果想解密該文件也很簡單,在SDK命令提示里輸入aspnet_regiis -pdf "配置節點名稱" "配置文件所在目錄(不是文件的物理路徑)"即可。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM