http://www.tuicool.com/articles/QvYbEn

一.EF,CodeFirst加密SQL连接符

public LifeHelpContext() : base("SQLConnectionString")
{ } public LifeHelpContext(string sql =@"DataSource=.;UserID=sa;Password=123456;InitialCatalog=TestDb;MultipleActiveResultSets=True;") : base(sql) //当sql省略时的时候,给定一个数据库连接字符串
{ }
LifeHelpContext继承的是 DbContext ,public LifeHelpContext() : base("SQLConnectionString"),可以是App.Config或(Web.config) 里的数据库连接字符串 Name值等。 数据库连接字符串: connectionString="Data Source=.;User ID=sa;Password=123456;Initial Catalog=TestDb;MultipleActiveResultSets=True;" /> <connectionStrings>
<add name="SQLConnectionString" providerName="System.Data.SqlClient"
connectionString="Data Source=.;User ID=sa;Password=123456;Initial Catalog=TestDb;MultipleActiveResultSets=True;" />
<add name="TestSQLConnection" providerName="System.Data.SqlClient"
connectionString="Data Source=.;User ID=sa;Password=123456;Initial Catalog=TestDb2;MultipleActiveResultSets=True;" />
</connectionStrings>
可以配置同一类型数据库不同地址,比如开发版、测试版等,也可以配置多数据库类型(EF支持的数据库(MSSQL、Oracle等)。也可以直接写 数据库连接,直接写数据库方便加密连接。 二.加密算法 2.1 加密用的是DES加密 为什么用DES? 一.DES是安全性比较高的一种算法,目前只有一种方法可以破解该算法,那就是穷举法. 二.采用64位密钥技术,实际只有56位有效,8位用来校验的.譬如,有这样的一台PC机器,它能每秒计算一百万次,那么256位空间它要穷举的时间为2285年.所以这种算法还是比较安全的一种算法. _iv = "67^%*(&(*Ghx7!rNIfb&95GUY86GfghUb#er57HBh(u%g6HJ($jhWk7&!hg4ui%$hjk"; //iv 向量
/// <summary>
/// 加密文本
/// </summary>
/// <param name="encryptoContext"></param>
/// <param name="cryptoKey"></param>
/// <returns></returns>
public string EncryptContext(string encryptoContext, string cryptoKey)
{
//取 8 位 key
cryptoKey = cryptoKey.PadLeft(8, '').Substring(0, 8);
//设置加密的 key,其值来自参数
byte[] key = Encoding.UTF8.GetBytes(cryptoKey);
//设置加密的 iv 向量,这里使用硬编码演示
byte[] iv = Encoding.UTF8.GetBytes(_iv);
//将需要加密的正文放进 byte 数组
byte[] context = Encoding.UTF8.GetBytes(encryptoContext);
using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
{
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(key, iv), CryptoStreamMode.Write))
{
cs.Write(context, 0, context.Length);
//将缓冲区数据写入,然后清空缓冲区
cs.FlushFinalBlock();
}
//从内存流返回结果,并编码为 base64string
return Convert.ToBase64String(ms.ToArray());
}
}
} 2.2 解密部分 /// <summary>
/// 解密文本
/// </summary>
/// <param name="decryptoContext"></param>
/// <returns></returns>
public string DecryptContext(string decryptoContext, string cryptoKey)
{
//取 8 位 key
cryptoKey = cryptoKey.PadLeft(8, '').Substring(0, 8);
//设置解密的 key,其值来自参数
byte[] key = Encoding.UTF8.GetBytes(cryptoKey);
//设置解密的 iv 向量,这里使用硬编码演示
byte[] iv = Encoding.UTF8.GetBytes(_iv);
//将解密正文返回到 byte 数组,加密时编码为 base64string ,这里要使用 FromBase64String 直接取回 byte 数组
byte[] context = Convert.FromBase64String(decryptoContext);
using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
{
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(key, iv), CryptoStreamMode.Write))
{
cs.Write(context, 0, context.Length);
//将当前缓冲区写入绑定的内存流,然后清空缓冲区
cs.FlushFinalBlock();
}
//从内存流返回值,并编码到 UTF8 输出原文
return Encoding.UTF8.GetString(ms.ToArray());
}
}
} 2.3 业务层,定义基类调用解密经过加密过的数据连接字符串 public class BllBase
{
protected readonly LifeHelpContext Dal;
protected BllBase()
{
FileEncrypt fileEncrypt = new FileEncrypt();
string trConnection = ConfigurationManager.ConnectionStrings["SQLConnectionString"].ConnectionString;
if (fileEncrypt.SqlConnectionIsEncrypted(trConnection,"19880125"))
{
trConnection = fileEncrypt.DecryptContext(trConnection);
}
Dal = new LifeHelpContext(trConnection);
}
}
/// <summary>
/// 验证是否符合指定的连接字符串格式
/// </summary>
/// <param name="content"></param>
/// <returns></returns>
public bool SqlConnectionIsEncrypted(string content)
{
Regex regex = new Regex(@"Data Source=(\S+);User ID=(\S+);Password=(\S+);Initial Catalog=(.+)");
return !regex.IsMatch(content);
}

一.EF,CodeFirst加密SQL连接符

public LifeHelpContext() : base("SQLConnectionString")
{ } public LifeHelpContext(string sql =@"DataSource=.;UserID=sa;Password=123456;InitialCatalog=TestDb;MultipleActiveResultSets=True;") : base(sql) //当sql省略时的时候,给定一个数据库连接字符串
{ }

LifeHelpContext继承的是 DbContext ,public LifeHelpContext() : base("SQLConnectionString"),可以是App.Config或(Web.config) 里的数据库连接字符串 Name值等。

数据库连接字符串:

connectionString="Data Source=.;User ID=sa;Password=123456;Initial Catalog=TestDb;MultipleActiveResultSets=True;" />

<connectionStrings>
<add name="SQLConnectionString" providerName="System.Data.SqlClient"
connectionString="Data Source=.;User ID=sa;Password=123456;Initial Catalog=TestDb;MultipleActiveResultSets=True;" />
<add name="TestSQLConnection" providerName="System.Data.SqlClient"
connectionString="Data Source=.;User ID=sa;Password=123456;Initial Catalog=TestDb2;MultipleActiveResultSets=True;" />
</connectionStrings>

可以配置同一类型数据库不同地址,比如开发版、测试版等,也可以配置多数据库类型(EF支持的数据库(MSSQL、Oracle等)。也可以直接写 数据库连接,直接写数据库方便加密连接。

二.加密算法

2.1 加密用的是DES加密

为什么用DES?

一.DES是安全性比较高的一种算法,目前只有一种方法可以破解该算法,那就是穷举法.

二.采用64位密钥技术,实际只有56位有效,8位用来校验的.譬如,有这样的一台PC机器,它能每秒计算一百万次,那么256位空间它要穷举的时间为2285年.所以这种算法还是比较安全的一种算法.

_iv = "67^%*(&(*Ghx7!rNIfb&95GUY86GfghUb#er57HBh(u%g6HJ($jhWk7&!hg4ui%$hjk"; //iv 向量
/// <summary>
/// 加密文本
/// </summary>
/// <param name="encryptoContext"></param>
/// <param name="cryptoKey"></param>
/// <returns></returns>
public string EncryptContext(string encryptoContext, string cryptoKey)
{
//取 8 位 key
cryptoKey = cryptoKey.PadLeft(8, '0').Substring(0, 8);
//设置加密的 key,其值来自参数
byte[] key = Encoding.UTF8.GetBytes(cryptoKey);
//设置加密的 iv 向量,这里使用硬编码演示
byte[] iv = Encoding.UTF8.GetBytes(_iv);
//将需要加密的正文放进 byte 数组
byte[] context = Encoding.UTF8.GetBytes(encryptoContext);
using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
{
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(key, iv), CryptoStreamMode.Write))
{
cs.Write(context, 0, context.Length);
//将缓冲区数据写入,然后清空缓冲区
cs.FlushFinalBlock();
}
//从内存流返回结果,并编码为 base64string
return Convert.ToBase64String(ms.ToArray());
}
}
}

2.2 解密部分

/// <summary>
/// 解密文本
/// </summary>
/// <param name="decryptoContext"></param>
/// <returns></returns>
public string DecryptContext(string decryptoContext, string cryptoKey)
{
//取 8 位 key
cryptoKey = cryptoKey.PadLeft(8, '0').Substring(0, 8);
//设置解密的 key,其值来自参数
byte[] key = Encoding.UTF8.GetBytes(cryptoKey);
//设置解密的 iv 向量,这里使用硬编码演示
byte[] iv = Encoding.UTF8.GetBytes(_iv);
//将解密正文返回到 byte 数组,加密时编码为 base64string ,这里要使用 FromBase64String 直接取回 byte 数组
byte[] context = Convert.FromBase64String(decryptoContext);
using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
{
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(key, iv), CryptoStreamMode.Write))
{
cs.Write(context, 0, context.Length);
//将当前缓冲区写入绑定的内存流,然后清空缓冲区
cs.FlushFinalBlock();
}
//从内存流返回值,并编码到 UTF8 输出原文
return Encoding.UTF8.GetString(ms.ToArray());
}
}
}

2.3 业务层,定义基类调用解密经过加密过的数据连接字符串

public class BllBase
{
protected readonly LifeHelpContext Dal;
protected BllBase()
{
FileEncrypt fileEncrypt = new FileEncrypt();
string trConnection = ConfigurationManager.ConnectionStrings["SQLConnectionString"].ConnectionString;
if (fileEncrypt.SqlConnectionIsEncrypted(trConnection,"19880125"))
{
trConnection = fileEncrypt.DecryptContext(trConnection);
}
Dal = new LifeHelpContext(trConnection);
}
}
/// <summary>
/// 验证是否符合指定的连接字符串格式
/// </summary>
/// <param name="content"></param>
/// <returns></returns>
public bool SqlConnectionIsEncrypted(string content)
{
Regex regex = new Regex(@"Data Source=(\S+);User ID=(\S+);Password=(\S+);Initial Catalog=(.+)");
return !regex.IsMatch(content);
}

EF--Codefirst 加密数据库连接字符串的更多相关文章

  1. Enterprise Library 中加密数据库连接字符串

    看了SHY520写的关于Data Access Application Block的文章,写得不错,忽略了一点就是如何去加密数据库连接字符串,这儿我简单的介绍一下.我们知道,在Enterprise L ...

  2. Winform RsaProtectedConfigurationProvider 加密数据库连接字符串

    private static string _strProvider = "RsaProtectedConfigurationProvider"; /// <summary& ...

  3. 创建自己的RSA密钥来保护web.config 加密数据库连接字符串

    通过创建自己的RSA密钥来保护web.config1创建RSA密钥:C:\Windows\Microsoft.NET\Framework64\v4.0.30319>aspnet_regiis - ...

  4. web config数据库连接字符串加密

    ASP.NET web.config中,数据库连接字符串的加密与解密 ASP.NET web.config中,数据库连接字符串的加密与解密. 开始--->运行,输入cmd,接着输入以下内容 加密 ...

  5. JavaScript日历控件开发 C# 读取 appconfig文件配置数据库连接字符串,和配置文件 List<T>.ForEach 调用异步方法的意外 ef 增加或者更新的习惯思维 asp.net core导入excel 一个二级联动

    JavaScript日历控件开发   概述 在开篇之前,先附上日历的代码地址和演示地址,代码是本文要分析的代码,演示效果是本文要实现的效果代码地址:https://github.com/aspwebc ...

  6. 关于IBatisNet的配置文件中数据库连接字符串加密处理

    我们通常在IBatisNet配置文件 properties.config 加入数据库连接字符串.数据库连接字符串直接放在里面,没有被加密,很不安全.如果我们把 properties.config 文件 ...

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

    ASP.NET web.config中,数据库连接字符串的加密与解密. 虽然不怎么新鲜,但相信还是有许多人不知道,好,不说废话,直接给方法:开始--->运行,输入cmd,接着输入以下内容 加密: ...

  8. asp.net web.config数据库连接字符串加密与解密

    在WEB网站开发过程中,如果我们将数据库连接字符串封装到.DLL文件中,将会给数据库和程序的迁移带来麻烦,因为万一服务器地址或者数据库发生变更,那么我们就不得不修改源程序并重新将其编译.最好的解决方法 ...

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

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

随机推荐

  1. 控件(选择类): Selector, ComboBox

    1.Selector(基类) 的示例Controls/SelectionControl/SelectorDemo.xaml <Page x:Class="Windows10.Contr ...

  2. matlab 获取鼠标位置

    转载:http://hi.baidu.com/alec1228/item/68ea36ebe4046f3a86d9deab 第一种途径:ginput()函数 ginput提供了一个十字光标使我们能更精 ...

  3. Firefox上运行自动化测试脚本提示元素无法点击“WebDriverException: Message: Element is not clickable at point“解决方法

    1. Firefox上运行脚本时提示“WebDriverException: Message: Element is not clickable at point (934.316650390625, ...

  4. BIEE定制化

    (1)自定义图片的引用 (2)修改产品本身的一些图片内容 (3)修改产品本身的一些文字 如何引用自己的自定义图片: 直接找路径或者图片就可以修改 推荐不要直接替换,直接替换导致有的内容没办法直接显示出 ...

  5. js-自制轮播插件!

    刚接触轮播的时候,感觉这种东西好高端,后来学习了jquery后,发现原来挺简单的,而且实现轮播也有很多形式,我用jquery自制了一个轮播插件,其实我这个说是插件,好像其实就是一个高度抽象的函数而已. ...

  6. 【bzoj1178】 Apio2009—CONVENTION会议中心

    http://www.lydsy.com/JudgeOnline/problem.php?id=1178 (题目链接) 题意 给出n个区间,问在区间两两不相交的情况下最多能选出多少区间,并输出字典序最 ...

  7. [NOIP2012] 提高组 洛谷P1084 疫情控制

    题目描述 H 国有 n 个城市,这 n 个城市用 n-1 条双向道路相互连通构成一棵树,1 号城市是首都, 也是树中的根节点. H 国的首都爆发了一种危害性极高的传染病.当局为了控制疫情,不让疫情扩散 ...

  8. dedecms /member/uploads_edit.php SQL Injection Vul

    catalog . 漏洞描述 . 漏洞触发条件 . 漏洞影响范围 . 漏洞代码分析 . 防御方法 . 攻防思考 1. 漏洞描述 Dedecms 5.3版本下的member/uploads_edit.p ...

  9. iOS开发者账号配置进行设备调试

    PS:我特么写了这么久,居然图片消失了,服了. 问题一:苹果开发者账号类型: 分为三种:个人的(99美金一年).组织的(99美金一年)和企业账号(299美金一年),申请时需要信用卡,可以找淘宝的代理申 ...

  10. 用Linux命令wget进行整站下载

    wget加上参数之后,即可成为相当强大的下载工具. wget -r -p -np -k http://xxx.com/abc/-r, --recursive(递归) specify recursive ...