有些项目尤其是WinForm或者是WPF项目,针对一些工具形式的小项目,不想软件流出去之后,懂程序的的拿到手之后一看配置文件就知道了我们数据库的用户名和密码,如果外网能访问的话,那就麻烦大了。所以这里为了防止项目外泄之后这些信息不被别人看到,我们就需要对链接字符串或者其他重要信息进行加密,用的时候在解密。

思路:使用两个数对连接字符串进行加密,再用这两个数进行解密。

    <add key="ConfigString" value="4HsXBRNXTkeN0ZoKdEwFE501TKSqLZUyJ0Zf+C7s5+gPd1SbWBiuh4PG6jeFgcnCTFr0QFW8FN40m/S8xmQq+8srL8taMLO23z6GSmaQJoM="/>

  

直接上代码:

1:定义一个初始化源数据的类。

    public class ConfigInformation
{
private static ConfigInformation _configInformation; public ConfigInformation Instance
{
get
{
if (_configInformation == null)
{
_configInformation = new ConfigInformation();
}
return _configInformation;
}
}
// 数据库链接字符串加解密 Key Value
public static String Key = "27e167e9-2660-4bc1-bea0-c8781a9f01cb";
public static String Vector = "8280d587-f9bf-4127-bbfa-5e0b4b672958"; }

  

2:加解密方法:

    /// <summary>
/// 加密 解密
/// </summary>
public class DecryptAndEncryptionHelper
{
private readonly SymmetricAlgorithm _symmetricAlgorithm;
private const String DefKey = "qazwsxedcrfvtgb!@#$%^&*(tgbrfvedcwsxqaz)(*&^%$#@!";
private String _key = "";
public String Key
{
get { return _key; }
set
{
if (!String.IsNullOrEmpty(value))
{
_key = value;
}
else
{
_key = DefKey;
}
}
} private const String DefIV = "tgbrfvedcwsxqaz)(*&^%$#@!qazwsxedcrfvtgb!@#$%^&*(";
private String _iv = "";
public String IV
{
get { return _iv; }
set
{
if (!String.IsNullOrEmpty(value))
{
_iv = value;
}
else
{
_iv = DefIV;
}
}
}
public DecryptAndEncryptionHelper()
{
_symmetricAlgorithm = new RijndaelManaged();
} public DecryptAndEncryptionHelper(String Key, String IV)
{
_symmetricAlgorithm = new RijndaelManaged();
_key = String.IsNullOrEmpty(Key) ? DefKey : Key;
_iv = String.IsNullOrEmpty(IV) ? DefIV : IV;
}
/// <summary>
/// Get Key
/// </summary>
/// <returns>密钥</returns>
private byte[] GetLegalKey()
{
_symmetricAlgorithm.GenerateKey();
byte[] bytTemp = _symmetricAlgorithm.Key;
int KeyLength = bytTemp.Length;
if (_key.Length > KeyLength)
_key = _key.Substring(0, KeyLength);
else if (_key.Length < KeyLength)
_key = _key.PadRight(KeyLength, '#');
return ASCIIEncoding.ASCII.GetBytes(_key);
} /// <summary>
/// Get IV
/// </summary>
private byte[] GetLegalIV()
{
_symmetricAlgorithm.GenerateIV();
byte[] bytTemp = _symmetricAlgorithm.IV;
int IVLength = bytTemp.Length;
if (_iv.Length > IVLength)
_iv = _iv.Substring(0, IVLength);
else if (_iv.Length < IVLength)
_iv = _iv.PadRight(IVLength, '#');
return ASCIIEncoding.ASCII.GetBytes(_iv);
} /// <summary>
/// Encrypto 加密
/// </summary>
public string Encrypto(string Source)
{
byte[] bytIn = UTF8Encoding.UTF8.GetBytes(Source);
MemoryStream ms = new MemoryStream();
_symmetricAlgorithm.Key = GetLegalKey();
_symmetricAlgorithm.IV = GetLegalIV();
ICryptoTransform encrypto = _symmetricAlgorithm.CreateEncryptor();
CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write);
cs.Write(bytIn, 0, bytIn.Length);
cs.FlushFinalBlock();
ms.Close();
byte[] bytOut = ms.ToArray();
return Convert.ToBase64String(bytOut);
} /// <summary>
/// Decrypto 解密
/// </summary>
public string Decrypto(string Source)
{
byte[] bytIn = Convert.FromBase64String(Source);
MemoryStream ms = new MemoryStream(bytIn, 0, bytIn.Length);
_symmetricAlgorithm.Key = GetLegalKey();
_symmetricAlgorithm.IV = GetLegalIV();
ICryptoTransform encrypto = _symmetricAlgorithm.CreateDecryptor();
CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Read);
StreamReader sr = new StreamReader(cs);
return sr.ReadToEnd();
}
}

  3:使用

// 获取加密的链接字符串,然后解密
string enString = ConfigurationManager.AppSettings["ConfigString"];
DecryptAndEncryptionHelper helper = new DecryptAndEncryptionHelper(ConfigInformation.Key, ConfigInformation.Vector); // 明文
var configStr = helper.Decrypto(enString);
return configStr;

  

这样至少保证了数据的不外泄。

注意:这个加密和解密的算法方法,应该放在服务器。通过请求加解密方法。不应该放在本地代码里,技术牛的的人,把你的项目反编译一样可以看到源代码。

 我们在把加密源数据找出来。

所以这个加解密代码不能写在本地,必须部署到安全的服务器上。

C# 数据库链接字符串加密工具的更多相关文章

  1. EF实体实现链接字符串加密

    1.加密解密方法 using System;using System.Security.Cryptography; using System.Text;namespace DBUtility{ /// ...

  2. sqlserver,sqlite,access数据库链接字符串

    SqlServer:string connection = "server=32.1.1.48;database=数据库名;user=sa;password=sa2008"; ac ...

  3. SqlServer数据库链接字符串

    完整链接字符串: 1."DataSourse=.\你的实例;Initial Catalog=yourdatabase;User ID=*;Password=*;Trusted_Connect ...

  4. Sql Server数据库链接字符串参数说明

               DataSource,//要连接到的 SQL Server 实例的名称或网络地址              FailoverPartner,//在主服务器停机时要连接到的伙伴服务 ...

  5. MSSQL数据库链接字符串Asynchronous Processing=true不是异步查询吗,怎么是缓存

    ;Asynchronous Processing=true  不是异步查询吗,怎么是缓存 <!--<add name="default" providerName=&q ...

  6. asp.net--常用的数据库链接字符串

    本地连接 privatestring conn_string ="Data Source=localhost;Initial Catalog=SQLtest;Integrated Secur ...

  7. kettle与各数据库建立链接的链接字符串

    kettle与各数据库建立链接的链接字符串 Sybase: TO_DB_URL = jdbc:sybase:Tds:192.168.168.163:5000/testdb?charset=eucgb& ...

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

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

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

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

随机推荐

  1. UIPassValue页面传值&nbsp;UI_08(下)

    2.从前一个界面到后一个界面 注意:解题思路  葵花宝典:属性传值  第一步:在下一个界面视图控制器的.h文件中定义一个属性  第二步:在push之前将数据存储到属性中  第三步:取出属性中的值让控件 ...

  2. javascript之prototype原型属性

    这个地方有点绕,仔细理解代码的意义. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " ...

  3. 【UI 设计】PhotoShop基础工具 -- 移动工具

    还是学点美工的东西吧, 业余爱好   比学编程还难 PS版本 : PhotoShop CS6 1. 移动工具 (1) 工具栏和属性栏 工具栏 和 属性栏 : 左侧的是工具栏, 每选中一个工具, 在菜单 ...

  4. Java进阶(二十六)公司项目开发知识点回顾

    公司项目开发知识点回顾 前言 "拿来主义"在某些时候并不是最佳选择,尤其是当自己遇到问题的时候,毫无头绪. 在一次实验过程中,需要实现数据库的CRUD操作.由于之前项目开发过程中, ...

  5. 《java入门第一季》之类(Scanner类)

    /* * Scanner:用于接收键盘录入数据. * * 前面的时候: * A:导包 * B:创建对象 * C:调用方法 * * System类下有一个静态的字段: * public static f ...

  6. 2013 QCon北京演讲:跨终端的WebKit渲染机制

    转载请注明原文地址:http://blog.csdn.net/milado_nju 1. 该演讲主要介绍WebKit的渲染机制的内部工作原理和一些新的技术,特别是针对不断出现的多种终端所做的一些努力. ...

  7. Java学习笔记(二)事件监听器

    Java实现对组件事件(如单击.输入等)的监听和JavaScript类似,都是先添加Listener,再写触发函数,不同的是,Java实现监听前必须使用implements将各个接口添加到类内. 相关 ...

  8. AngularJS进阶(一)深入理解ANGULARUI路由_UI-ROUTER

    深入理解ANGULARUI路由_UI-ROUTER 最近在用 ionic写个webapp 看到几个demo中路由有好几种,搞的有点晕,查下资料研究下,做个笔记,其中大部分为摘抄别人的,做个说明免得被人 ...

  9. Android百分比布局支持库(android-percent-support)

    Android中提供了五种布局,其中用的最多的就是:LinearLayout, RelativeLayout 和 FrameLayout这三种布局,在对某一界面进行布局时最先想到也是通过这三种来布局的 ...

  10. Shell编程入门(第二版)(下)

    ... ... command n done #select把关键字中的每一项做成类似表单,以交互的方式执行do和done之间的命令 示例-select.sh [python] view plainc ...