[恶心]数据库连接串加密
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.Common; namespace System.Data { /// <summary> /// MultipleActiveResultSets=True; /// </summary> [Serializable] public sealed class ConnectionStringBuilder : DbConnectionStringBuilder { #region Properties public bool IsEncrypt { get { return base.ContainsKey("KEY"); } } public string[] CryptoKeys { set { if (value.Length < 2) { throw new ArgumentException("value.Length < 2"); } base["KEY"] = string.Join(DbUtility.Separator, value); } get { object value; if (base.TryGetValue("KEY", out value)) { string[] args = value.ToString().Split(DbUtility.Separator[0]); if (args.Length >= 2) { return args; } } return new string[2]; } } #endregion #region Methods public ConnectionStringBuilder() { } public ConnectionStringBuilder(string connectionString) { base.ConnectionString = connectionString; } internal string GetDecrypt() { if (this.IsEncrypt) { string[] args = this.CryptoKeys; using (CryptoManaged coder = new CryptoManaged(args[0], args[1])) { return coder.Decrypt(base["ENTITY"].ToString()); } } return base.ConnectionString; } public override string ToString() { if (this.IsEncrypt) { string[] args = this.CryptoKeys; using (CryptoManaged coder = new CryptoManaged(args[0], args[1])) { base.Remove("KEY"); string oldString = base.ConnectionString; base.Clear(); base["ENTITY"] = coder.Encrypt(oldString); this.CryptoKeys = args; string newString = base.ToString().Replace("\"", string.Empty); base.ConnectionString = oldString; this.CryptoKeys = args; return newString; } } return base.ToString(); } #endregion } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace Rocky.App { public partial class ConnectionStringForm : Form { private ConnectionStringBuilder builder; public ConnectionStringForm() { InitializeComponent(); } private void ConnectionStringForm_Load(object sender, EventArgs e) { builder = new ConnectionStringBuilder(); } private void textBox1_Enter(object sender, EventArgs e) { if (Clipboard.ContainsText()) { textBox1.Text = Clipboard.GetText(); } } private void button1_Click(object sender, EventArgs e) { builder.ConnectionString = textBox1.Text; builder.CryptoKeys = new string[] { CryptoManaged.MD5Hex("Rocky.TBox"), CryptoManaged.NewSalt }; textBox2.Text = builder.ToString(); } } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<connectionStrings> <add name="access" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|#xfjob.mdb" providerName="System.Data.OleDb"/> </connectionStrings>