zoukankan      html  css  js  c++  java
  • EF--Codefirst 加密数据库连接字符串

    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)
    {
      //8key
      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)
    {
      //8key
      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加密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);
    }
  • 相关阅读:
    django页面分类和继承
    django前端从数据库获取请求参数
    pycharm配置django工程
    django 应用各个py文件代码
    CF. 1428G2. Lucky Numbers(背包DP 二进制优化 贪心)
    HDU. 6566. The Hanged Man(树形背包DP DFS序 重链剖分)
    小米邀请赛 决赛. B. Rikka with Maximum Segment Sum(分治 决策单调性)
    区间树 学习笔记
    CF GYM. 102861M. Machine Gun(主席树)
    2016-2017 ACM-ICPC East Central North America Regional Contest (ECNA 2016) (B, D, G, H)
  • 原文地址:https://www.cnblogs.com/shiningrise/p/5603307.html
Copyright © 2011-2022 走看看