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>

 

using System;
using System.Configuration;
using System.Collections.Generic;
namespace HTL{
    static class Program{
        /// <summary>
        /// 健值集合,用於保存數據到配置文件
        /// </summary>
        static Dictionary<string, string> key_value = new Dictionary<string, string>();
        [STAThread]
        public static void Main(string[] args)
        {
            key_value.Add("encrypt","加密");
            key_value.Add("test","測試");
            
            //加密AppSettings節點
            AddConfig(key_value,true);
            try    {
                Console.WriteLine("加密'test'的數據:"+System.Configuration.ConfigurationManager.AppSettings["test"]);
            }
            catch(Exception e)
            {
                Console.Write("讀取AppSettings節點數據失敗.錯誤信息:\r\n"+e.Message );
            }      
            //不加密AppSettings節點,如果不加密在前,加密在后則會出現錯誤“無法識別的屬性“configProtectionProvider”。請注意屬性名稱區分大小寫。”
                        AddConfig(key_value,false);
            try    {
                Console.WriteLine("未加密'test'的數據:"+System.Configuration.ConfigurationManager.AppSettings["test"]);
            }
            catch(Exception e)
            {
                Console.Write("讀取AppSettings節點數據失敗.錯誤信息:\r\n"+e.Message );
            }              
            Console.ReadKey();
        }
        /// <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);
            #region  //循環添加或更改健值
            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);
            }//end foreach
            #endregion
            #region//保存配置文件
            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");   
        ConfigurationManager.RefreshSection("configuration");
           }
       #endregion
        }
}  
View Code

 

AddConfig ( key_value , true ); //加密AppSettings節點
加密在前,不加密在后
不加密在前,加密在后出錯的錯誤
配置文件加密參考:
 
無法識別的屬性 configProtectionProvider參考(都未解決):


免責聲明!

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



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