首先是加密,解密类。

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(, ));
des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(, ));
System.IO.MemoryStream ms = new System.IO.MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, , 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 / ;
byte[] inputByteArray = new byte[len];
int x, i;
for (x = ; x < len; x++)
{
i = Convert.ToInt32(Text.Substring(x * , ), );
inputByteArray[x] = (byte)i;
}
des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(, ));
des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(, ));
System.IO.MemoryStream ms = new System.IO.MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, , 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 = { , , , , , , , , , , , , , , , , , , , , , , , }; //定义密钥
byte[] IV = { , , , , , , , }; //定义偏移量
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, , 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 = { , , , , , , , , , , , , , , , , , , , , , , , }; //定义密钥
byte[] IV = { , , , , , , , }; //定义偏移量
TripleDESCryptoServiceProvider TripleDES = new TripleDESCryptoServiceProvider();
TripleDES.IV = IV;
TripleDES.Key = key;
ICryptoTransform encrypto = TripleDES.CreateDecryptor();
System.IO.MemoryStream ms = new System.IO.MemoryStream(bytIn, , 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);
}
}
}
}

加密使用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;
}
}

加密的原因是,为客户开发的某些程序,需要访问公司(我们自己工作的)在公网的数据库,但是我们不能将明文数据库访问字符串,存放在客户的应用程序上,最好的办法就是将其加密。下面就在一个为客户开发的程序中使用这个加密连接。这里,我将密钥和密文都写在了配置文件中。如果用户猜出我的加密算法,他们可以根据密钥,可以轻松获得我的明文。所以,不要傻到直接将密钥配置命名成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 / ;
byte[] inputByteArray = new byte[len];
int x, i;
for (x = ; x < len; x++)
{
i = Convert.ToInt32(Text.Substring(x * , ), );
inputByteArray[x] = (byte)i;
}
des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(, ));
des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(, ));
System.IO.MemoryStream ms = new System.IO.MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, , inputByteArray.Length);
cs.FlushFinalBlock();
return Encoding.Default.GetString(ms.ToArray());
}
}

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

connectionString加密的更多相关文章

  1. 对web.config的ConnectionString加密

    原文:对web.config的ConnectionString加密 本文参考了wayshan的博客,原文地址:http://www.cnblogs.com/wayshan/archive/2012/0 ...

  2. .NET安全审核检查表

    书籍名称:Web安全设计之道 -.NET代码安全,界面漏洞防范与程序优化   .NET安全审核检查表   检查项 任务描述 设计环节     Security descisions should no ...

  3. NBIbatis 基础框架

    基础框架 NBIbatis 为真实在用的系统中剥离出的一个ibatis.net应用框架,目的在于通过此项目让软件工程师集中关注表现层及业务规则编写. 通过数据访问和业务规则可快速搭建不同表现形式的网站 ...

  4. ASP.NET MVC系列:web.config中ConnectionString aspnet_iis加密与AppSettings独立文件

    1. web.config中ConnectionString aspnet_iis加密 web.config路径:E:\Projects\Libing.Web\web.config <conne ...

  5. 【转】Encrypt ConnectionString in Web.Config 【加密ASP.NET web.config数据库链接字串】

    原文链接:https://www.codeproject.com/Tips/795135/Encrypt-ConnectionString-in-Web-Config web.config中一般会存放 ...

  6. 如何对ConnectionString进行加密解码?

    这个就不说了就是一个类 public static class EncryptionConfig { /* 加密配置节点 * Response.Write(EncryptionConfig.Encry ...

  7. ASP.NET加密和解密数据库连接字符串

    大家知道,在应用程序中进行数据库操作需要连接字符串,而如果没有连接字符串,我们就无法在应用程序中完成检索数据,创建数据等一系列的数据库操作.当有人想要获取你程序中的数据库信息,他首先看到的可能会是We ...

  8. C# salt+hash 加密

    一.先明确几个基本概念 1.伪随机数:pseudo-random number generators ,简称为:PRNGs,是计算机利用一定的算法来产生的.伪随机数并不是假随机 数,这里的" ...

  9. ASP.NET MVC5+EF6+EasyUI 后台管理系统(62)-EF链接串加密

    系列目录 前言: 这一节提供一个简单的功能,这个功能看似简单,找了一下没找到EF链接数据库串的加密帮助文档,只能自己写了,这样也更加符合自己的加密要求 有时候我们发布程序为了避免程序外的SQL链接串明 ...

随机推荐

  1. ORM原型概念

    ORM[Object-Relation-Mapping]对象关系映射. 这个名词已经出来好几年了.已经不陌生.  以前在项目中针对相对复杂业务逻辑时一般采用领域模型驱动方式进行业务概述,分析和建模. ...

  2. Rhel6-cacti+nagios+ganglia(nginx)配置文档

    (lnmp平台) 系统环境: rhel6 x86_64 iptables and selinux disabled 主机: 192.168.122.185 server85.example.com 1 ...

  3. xcode代码提示功能失效的解决方法

    xcode 自动提示很好用 然而大量的工作也是让他吃不消了 结果今天提示功能给我来了个罢工 这当然是不行的 也是万能的搜索帮我解决了这个问题 方法很多 选择了简单的 xcode --> Wind ...

  4. JS rem 设置

    (function () { var docEl = document.documentElement; var resize = 'orientationchange' in window ? 'o ...

  5. React Native的组件ListView

    React Native的组件ListView类似于iOS中的UITableView和UICollectionView,也就是说React Native的组件ListView既可以实现UITableV ...

  6. PCL中point cloud的数据类型

    出处: http://wiki.ros.org/pcl/Overview 1.数据类型 1.1 ROS中point cloud数据类型 sensor mesgs::PointCloud sensor ...

  7. Node.js高级编程读书笔记 - 1 基本概念

    Outline 1 概述和安装 1.1 安装Node 1.2 Node简介 2 Node核心API基础 2.1 加载模块 2.2 应用缓冲区处理.编码和解码二进制数据 2.3 使用时间发射器模式简化事 ...

  8. 腾讯优测优分享 | 探索react native首屏渲染最佳实践

    腾讯优测是专业的移动云测试平台,旗下的优分享不定时提供大量移动研发及测试相关的干货~ 此文主要与以下内容相关,希望对大家有帮助. react native给了我们使用javascript开发原生app ...

  9. 新冲刺Sprint3(第三天)

    一.Sprint会议 更新商品价格.商品描述功能已经完成了,搜索商品功能也正在准备了. 以下是部分功能真机测试下的效果图:     二.Sprint周期 看板: 燃尽图:

  10. SQLite建表并添加数据