connectionString加密

本文介绍了一种用于保护数据库访问字符串免受非法访问的加密技术,通过使用MD5和TripleDES算法对连接字符串进行加密,并提供了解密方法。加密和解密类的实现确保了敏感信息的安全性,同时在配置文件中存储密钥和密文以增加安全性。通过在应用中使用此加密连接字符串,可以防止未经授权的访问。

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

首先是加密,解密类。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace SqlConnectionEncryp
{
    public class Encrypt
    {
        /// <summary> 
        ///  MD5加密 
        /// </summary> 
        public static string MD5Encrypt(string Text, string sKey)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] 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();
        }

        /// <summary> 
        ///  MD5解密
        /// </summary>  
        public static string MD5Decrypt(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());
        }


        /// <summary>
        /// TripleDES加密
        /// </summary>
        public static string TripleDESEncrypting(string strSource)
        {
            try
            {
                byte[] bytIn = Encoding.Default.GetBytes(strSource);
                byte[] key = { 42, 16, 93, 156, 78, 4, 218, 32, 15, 167, 44, 80, 26, 20, 155, 112, 2, 94, 11, 204, 119, 35, 184, 197 }; //定义密钥
                byte[] IV = { 55, 103, 246, 79, 36, 99, 167, 3 };  //定义偏移量
                TripleDESCryptoServiceProvider TripleDES = new TripleDESCryptoServiceProvider();
                TripleDES.IV = IV;
                TripleDES.Key = key;
                ICryptoTransform encrypto = TripleDES.CreateEncryptor();
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write);
                cs.Write(bytIn, 0, bytIn.Length);
                cs.FlushFinalBlock();
                byte[] bytOut = ms.ToArray();
                return System.Convert.ToBase64String(bytOut);
            }
            catch (Exception ex)
            {
                throw new Exception("加密时候出现错误!错误提示:\n" + ex.Message);
            }
        }

        /// <summary>
        /// TripleDES解密
        /// </summary>
        public static string TripleDESDecrypting(string Source)
        {
            try
            {
                byte[] bytIn = System.Convert.FromBase64String(Source);
                byte[] key = { 42, 16, 93, 156, 78, 4, 218, 32, 15, 167, 44, 80, 26, 20, 155, 112, 2, 94, 11, 204, 119, 35, 184, 197 }; //定义密钥
                byte[] IV = { 55, 103, 246, 79, 36, 99, 167, 3 };   //定义偏移量
                TripleDESCryptoServiceProvider TripleDES = new TripleDESCryptoServiceProvider();
                TripleDES.IV = IV;
                TripleDES.Key = key;
                ICryptoTransform encrypto = TripleDES.CreateDecryptor();
                System.IO.MemoryStream ms = new System.IO.MemoryStream(bytIn, 0, bytIn.Length);
                CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Read);
                StreamReader strd = new StreamReader(cs, Encoding.Default);
                return strd.ReadToEnd();
            }
            catch (Exception ex)
            {
                throw new Exception("解密时候出现错误!错误提示:\n" + ex.Message);
            }
        }
    }
}
View Code

加密使用MD5Decrypt,自己给定一个密钥。下面是对连接字符串加密的界面:

代码和测试效果:

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnCreate_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtClear.Text))
            {
                MessageBox.Show("明文不能为空!");
            }
            if (string.IsNullOrEmpty(txtKey.Text))
            {
                MessageBox.Show("密钥不能为空!");
            }

            string strCipher = Encrypt.MD5Encrypt(txtClear.Text, txtKey.Text);
            txtCipher.Text = strCipher;
        }
    }
View Code

加密的原因是,为客户开发的某些程序,需要访问公司(我们自己工作的)在公网的数据库,但是我们不能将明文数据库访问字符串,存放在客户的应用程序上,最好的办法就是将其加密。下面就在一个为客户开发的程序中使用这个加密连接。这里,我将密钥和密文都写在了配置文件中。如果用户猜出我的加密算法,他们可以根据密钥,可以轻松获得我的明文。所以,不要傻到直接将密钥配置命名成key。如果将密钥写死在代码中就不方便控制,客户反编译同样能获知加密算法和密钥,从而获得本来的连接字符串。

下面在获取连接字符串时,都要对其进行解密,所以构造一个解密类是必要的。

public class ConfigHelper
    {
        /// <summary>
        /// 获取普通连接
        /// </summary>
        public static string GetConn(string conn)
        {
            return ConfigurationManager.ConnectionStrings[conn].ConnectionString;
        }
        /// <summary>
        /// 获取appsetting
        /// </summary>
        public static string GetAppSetting(string key)
        {
            return ConfigurationManager.AppSettings[key];
        }
        /// <summary>
        /// 获取解密连接
        /// </summary>
        public static string GetConn(string conn, string key)
        {
            string strConn = GetConn(conn);
            string strKey = GetAppSetting(key);
            return MD5Decrypt(strConn, strKey);
        }

        /// <summary> 
        ///  MD5解密
        /// </summary>  
        private static string MD5Decrypt(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());
        }
    }
View Code

下面是解密效果,如果客户不是专业人士,我们公网数据库连接就是安全的了:

 

用于加密.net WebForm的Web.Config文件中的数据库连接字符串. 本软件支持.net 2.0 和 .net 4.0. 注意事项: 1.需要安装.net4.0运行库才能运行. 2.程序中需要获取web.config路径时,可以使用复制把web.config所在路径粘贴到程序中.快捷键不是Ctrl + V而是右键选择"编辑"-"粘贴".如果右键点击程序窗口无效,可以右键点击程序标题栏. 扩展知识: 连接字符串的安全性 一、尽量使用windows验证而不是sql server验证: 1、安全性易管理 2、不需要设置用户名和密码(这样传递的时候不会被截取吧) 3、密码不会通过明文在网络上传播 原因:如果用sql server验证在配置文件中的话,用户名和密码很容易被别人看到,但是如果你用windows验证的话,用户名和密码是存储在本机windows文件中的 这就很难被人发现。 二、sql server身份验证 1、强制实施密码策略 2、强制密码过期 3、用户在下次登录时必须更改密码 怎么设置:直接在sql server中进行设置 如果是sql server验证的话,Persist security info 一定设置为false,这样会保证敏感信息不被暴露(如ID、密码)。 三、防止sql注入攻击: 这个注入好像是打开Min Pool Size=999999一个很大的值,来破坏数据库。 这个链接保护的方法最好是: Date Source=(local);Initial Catalog=Works;User ID=sa;Password="password01!;Pooling=true" 看到后面没有,加一个双引号。 四、在配置文件存储链接字符串: <configuration> <connectionStrings configSource="connection.config"> </configuration> 然后在connection.config里有这样的设置: <connectionStrings> <add name="AW" connectionString="server......"> </connectionStrings> 注意:connection.config属性需要设置,设置为复制到应用程序里面。不然web.config就找不到这个文件。 五、用RSA非对称加密。网上查。 六、asp.net iis注册工具(aspnet_regiis.exe) 使用加密:aspnet_regiis -pef "connectionStrings" F:\study\ComputerDM\Web 解密:aspnet_regiis -pdf "connectionStrings" F:\study\ComputerDM\Web
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值