winform 加密连接数据库

本文介绍了一种在应用程序启动时加密数据库连接字符串的方法,通过读取配置文件中的连接信息,并使用DES算法进行加密处理,有效保护了数据库的安全。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在app.config中有配置代码如下:

<configuration>
  <appSettings>
    <add key="ConStringEncrypt" value="false" />
    <add key="ConnectionString" value="Server=localhost;Database=testmysql;User=root;Password=xiaowei;Port=3306;Charset=utf8" />
  </appSettings>

</configuration>

在程序开始运行处加密数据库连接信息,防止别人盗用数据库密码信息

 static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            // 链接字符串加密
            string ConStringEncrypt = ConfigurationManager.AppSettings["ConStringEncrypt"];
            string _connectionString = ConfigurationManager.AppSettings["ConnectionString"]; 
            if (ConStringEncrypt == "false")
            {
                _connectionString = DESEncrypt.Encrypt(_connectionString);
                // 写入到config文件中
              SetValue(Application.ExecutablePath + ".config",  "ConStringEncrypt", "true");
                SetValue(Application.ExecutablePath + ".config",  "ConnectionString", _connectionString);                 
            }


            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new FormMain());
        }

}

 public static void SetValue(string configPath, string AppKey, string AppValue)
        {
            XmlDocument xDoc = new XmlDocument();
            //获取可执行文件的路径和名称
            xDoc.Load(configPath);
            XmlNode xNode;
            XmlElement xElem1;
            XmlElement xElem2;
            xNode = xDoc.SelectSingleNode("//appSettings");
            xElem1 = (XmlElement)xNode.SelectSingleNode("//add[@key='" + AppKey + "']");
            if (xElem1 != null) xElem1.SetAttribute("value", AppValue);
            else
            {
                xElem2 = xDoc.CreateElement("add");
                xElem2.SetAttribute("key", AppKey);
                xElem2.SetAttribute("value", AppValue);
                xNode.AppendChild(xElem2);
            }
            xDoc.Save(configPath);
        }
    }

一下是加密解密程序:

public class DESEncrypt
{
public DESEncrypt()
{
}


#region ========加密======== 
 
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="Text"></param>
        /// <returns></returns>
public static string Encrypt(string Text) 
{
            return Encrypt(Text, "Otitan");
}
/// <summary> 
/// 加密数据 
/// </summary> 
/// <param name="Text"></param> 
/// <param name="sKey"></param> 
/// <returns></returns> 
public static string Encrypt(string Text,string sKey) 

DESCryptoServiceProvider des = new DESCryptoServiceProvider(); 
byte[] inputByteArray; 
inputByteArray=Encoding.Default.GetBytes(Text); 
des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8)); 
des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8)); 
System.IO.MemoryStream ms=new System.IO.MemoryStream(); 
CryptoStream cs=new CryptoStream(ms,des.CreateEncryptor(),CryptoStreamMode.Write); 
cs.Write(inputByteArray,0,inputByteArray.Length); 
cs.FlushFinalBlock(); 
StringBuilder ret=new StringBuilder(); 
foreach( byte b in ms.ToArray()) 

ret.AppendFormat("{0:X2}",b); 

return ret.ToString(); 



#endregion

#region ========解密======== 
   
 
        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="Text"></param>
        /// <returns></returns>
public static string Decrypt(string Text) 
{
            return Decrypt(Text, "Otitan");
}
/// <summary> 
/// 解密数据 
/// </summary> 
/// <param name="Text"></param> 
/// <param name="sKey"></param> 
/// <returns></returns> 
public static string Decrypt(string Text,string sKey) 

DESCryptoServiceProvider des = new DESCryptoServiceProvider(); 
int len; 
len=Text.Length/2; 
byte[] inputByteArray = new byte[len]; 
int x,i; 
for(x=0;x<len;x++) 

i = Convert.ToInt32(Text.Substring(x * 2, 2), 16); 
inputByteArray[x]=(byte)i; 

des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8)); 
des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8)); 
System.IO.MemoryStream ms=new System.IO.MemoryStream(); 
CryptoStream cs=new CryptoStream(ms,des.CreateDecryptor(),CryptoStreamMode.Write); 
cs.Write(inputByteArray,0,inputByteArray.Length); 
cs.FlushFinalBlock(); 
return Encoding.Default.GetString(ms.ToArray()); 

 
#endregion 




}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值