首先是加密,解密类。

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. Windows与Linux主机之间的连接和交互工具

    1.Putty 远程连接Linux主机 Windows主机上安装putty,工具打开后显示如下: 输入要连接的Linux主机的IP地址,点击Load,连接主机后输入用户名密码,即可登录Linux主机 ...

  2. Foundation框架—集合

    Foundation框架—集合 一.NSArray和NSMutableArray (一)NSArray不可变数组 (1)NSArray的基本介绍 NSArray是OC中使用的数组,是面向对象的,以面向 ...

  3. iOS开发网络篇—HTTP协议

    iOS开发网络篇—HTTP协议 说明:apache tomcat服务器必须占用8080端口 一.URL 1.基本介绍 URL的全称是Uniform Resource Locator(统一资源定位符) ...

  4. yii2.0高级框架配置时打开init.bat秒退的解决方法 (两种方法)

    第一种: 这几天刚接触到yii2.0框架,在配置advanced版本时运行init.bat初始化文件时老是闪退: 用cmd运行该文件时显示:The OpenSSL PHP extension is r ...

  5. Linux下SVN命令

    一下内容转载于:http://blog.chinaunix.net/space.php?uid=22976768&do=blog&id=1640924.这个总结的很好~ windows ...

  6. Java类的成员函数调用顺序

    class A { public A() { System.out.println("----------A 构造-------------"); } static void sb ...

  7. IT公司100题-tencent-打印所有高度为2的路径

    问题描述: 打印所有到叶子节点长度为2的路径  10  /  \ 6   16 / \   / \ 4 8  14 18   / \    / \    \ 2  5  12 15 20 / 11   ...

  8. Python学习笔记-字典

    字典是python中唯一内建的映射类型. 创建字典phonebook = {'Alice':'2341','Beth':'9102'} 可以使用dict通过其他映射或者键值对的序列建立字典.关键值参数 ...

  9. SharePoint 2013 开发——其他社交功能

    博客地址:http://blog.csdn.net/FoxDave 上一篇讲了如何获取用户配置文件的相关属性,它属于SharePoint 2013社交功能的一个小的构成部分.社交功能是SharePoi ...

  10. Android Studio实现页面跳转(新页面或者网站)

    一,跳转到另一个页面 百度了好久,好像好多种方法,从中挑选了一中比较方便的一中方法 利用Intent类进行实现 1,首先在firstActivity中添加相应的跳转命令代码 例如一下示例代码 if ( ...