<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 } }
C# 对 App.config的appSettings节点数据进行加密,布布扣,bubuko.com
C# 对 App.config的appSettings节点数据进行加密
原文:http://www.cnblogs.com/huangtailang/p/3925275.html