运行时动态设置并加密App.Config中的数据库连接字符串

  App.config中的数据库连接字符串,是在Settings.settings同步过来的。后者在设计时支持数据集DataSet的设计,但运行时不能更改,可以更改App.config的连接字符串,但无法加密、解密。造成的结果是数据库连接字符串,要么固定不变,要么以明文显示,极不安全。多次尝试后,成功的解决这些问题。


我的经验:

  1. Settings.settings中的设置和App.config中的设置会相互更新,彼此同步。前者用于设计支持,后者用于运行时。可以手工阻止两者同步,使两者设置不一样,如果没有发布App.config,则全部采用Settings.settings的设置;否则在运行时App.config会覆盖Settings.settings的设置。

  2. Settings.settings中的Application范围设置只在设计时更改,是只读的属性,User范围设置可以在运行时读写。参考MSDN文章“在 C# 中使用设置”中的说明:
应用程序作用域设置与用户作用域设置之间的重要区别是,用户作用域设置在运行时为读/写,并且可在代码中对其值进行更改和保存。应用程序作用域设置在运行时为只读。虽然可以读取,但是不能对其进行写入。具有应用程序作用域的设置只能在设计时或通过手动修改设置文件进行更改。

   3. Settings中的只有“连接字符串”设置才能被数据集DataSet设计时支持,而“连接字符串”设置只能是Application范围设置,是只读的属性。


解决思路:
  将Settings.settings的设计时代码文件Settings.Designer.cs内容复制到Setgings.cs中,删除Settings.Designer.cs,更改部分代码。连接字符串在Setgings.cs中缺省设置为明码,在App.config中为加密码。代码如下,DESEncrypt为静态加密函数,DESDecrypt为静态解密函数:

ContractedBlock.gif ExpandedBlockStart.gif 重写Settings代码
 1None.gifusing System.Xml;
 2None.gifnamespace A.Properties
 3ExpandedBlockStart.gifContractedBlock.gifdot.gif{
 4InBlock.gif
 5InBlock.gif    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
 6InBlock.gif    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator""8.0.0.0")]
 7InBlock.gif    internal sealed  class Settings : global::System.Configuration.ApplicationSettingsBase
 8ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
 9InBlock.gif
10InBlock.gif        private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
11InBlock.gif
12InBlock.gif        public static Settings Default
13ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
14InBlock.gif            get
15ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
16InBlock.gif                return defaultInstance;
17ExpandedSubBlockEnd.gif            }

18ExpandedSubBlockEnd.gif        }

19InBlock.gif
20InBlock.gif        [global::System.Configuration.ApplicationScopedSettingAttribute()]
21InBlock.gif        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
22InBlock.gif        [global::System.Configuration.SpecialSettingAttribute(global::System.Configuration.SpecialSetting.ConnectionString)]
23InBlock.gif        [global::System.Configuration.DefaultSettingValueAttribute("Data Source=(local);Initial Catalog=Test;Persist Security Info=True;User ID=sa;Password=")]
24InBlock.gif        public string ConnectionString1
25ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
26InBlock.gif            get
27ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
28InBlock.gif                return Encrypt.DESDecrypt(this["ConnectionString1"].ToString());
29ExpandedSubBlockEnd.gif            }

30InBlock.gif            set
31ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
32InBlock.gif                base["ConnectionString1"= Encrypt.DESEncrypt(value);
33InBlock.gif                this.SetKeyValue("A.Properties.Settings.ConnectionString1", Encrypt.DESEncrypt(value));
34ExpandedSubBlockEnd.gif            }

35ExpandedSubBlockEnd.gif        }

36InBlock.gif
37InBlock.gif
38ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
39InBlock.gif        /// 保存设置
40InBlock.gif        /// </summary>
41InBlock.gif        /// <param name="AppKey"></param>
42ExpandedSubBlockEnd.gif        /// <param name="AppValue"></param>

43InBlock.gif        private void SetKeyValue(string AppKey, string AppValue)
44ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
45InBlock.gif            XmlDocument xDoc = new XmlDocument();
46InBlock.gif            xDoc.Load(System.Windows.Forms.Application.ExecutablePath + ".config");
47InBlock.gif
48InBlock.gif            XmlNode xNode;
49InBlock.gif            XmlElement xElem1;
50InBlock.gif            XmlElement xElem2;
51InBlock.gif
52InBlock.gif            xNode = xDoc.SelectSingleNode("//connectionStrings");
53InBlock.gif
54InBlock.gif            xElem1 = (XmlElement)xNode.SelectSingleNode("//add[@name='" + AppKey + "']");
55InBlock.gif            if (xElem1 != null) xElem1.SetAttribute("connectionString", AppValue);
56InBlock.gif            else
57ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
58InBlock.gif                xElem2 = xDoc.CreateElement("add");
59InBlock.gif                xElem2.SetAttribute("name", AppKey);
60InBlock.gif                xElem2.SetAttribute("connectionString", AppValue);
61InBlock.gif                xNode.AppendChild(xElem2);
62ExpandedSubBlockEnd.gif            }

63InBlock.gif            xDoc.Save(System.Windows.Forms.Application.ExecutablePath + ".config");
64ExpandedSubBlockEnd.gif        }

65InBlock.gif
66InBlock.gif
67ExpandedSubBlockEnd.gif    }

68ExpandedBlockEnd.gif}

69None.gif

默认情况下,新的连接字符串设置只在重启时生效。但可以操作数据前,加上一条更改Dataset中Adapter的连接字符串的语句,就可以不用重启,代码如下:

ContractedBlock.gif ExpandedBlockStart.gif 运行更改数据库连接
 1None.gif        private void toolStripButton1_Click(object sender, EventArgs e)
 2ExpandedBlockStart.gifContractedBlock.gif        dot.gif{
 3InBlock.gif            A.Properties.Settings.Default.ConnectionString1 = @"Data Source=(local);Initial Catalog=Test2;Persist Security Info=True;User ID=sa";
 4InBlock.gif
 5InBlock.gif            this.toolStripTextBox1.Text = A.Properties.Settings.Default.ConnectionString1;
 6InBlock.gif            this.Test1TableAdapter.Connection.ConnectionString = A.Properties.Settings.Default.ConnectionString1;
 7InBlock.gif            MessageBox.Show(A.Properties.Settings.Default.ConnectionString1);
 8InBlock.gif            this.Test1TableAdapter.Fill(this.dataSet1.Test1);
 9InBlock.gif
10ExpandedBlockEnd.gif        }

 

转载于:https://www.cnblogs.com/drc/archive/2006/10/11/526193.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值