数据库连接的安全保障

文章目录

    • 1 SQLHelper类的编写
    • 2 配置文件的使用
      • 2.1 连接字符串存在的问题
      • 2.2 配置文件的使用
      • 2.3 使用配置文件常见错误
      • 2.4 配置文件总结
    • 3 字符串的安全问题

1 SQLHelper类的编写

在DAL中添加Helper文件夹,并添加SQLHelper类。
数据库连接的安全保障_第1张图片

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Data;
using System.Data.SqlClient;

using System.Configuration;//引入读取配置文件的命名空间

namespace DAL
{
    /// 
    /// 通用数据访问类
    /// 
    public class SQLHelper
    {
        private static string connString = "Server=aaaa\\sqlexpress;DataBase=StudentManageDB;Uid=sa;Pwd=password01!";
        
        /// 
        /// 执行增、删、改方法
        /// 
        /// 
        /// 
        public static int Update(string sql)
        {
            SqlConnection conn = new SqlConnection(connString);
            SqlCommand cmd = new SqlCommand(sql, conn);
            try
            {
                conn.Open();
                return cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                //将错误信息写入日志...

                throw ex;
            }
            finally
            {
                conn.Close();
            }
        }
        /// 
        /// 执行单一结果(select)
        /// 
        /// 
        /// 
        public static object GetSingleResult(string sql)
        {
            SqlConnection conn = new SqlConnection(connString);
            SqlCommand cmd = new SqlCommand(sql, conn);
            try
            {
                conn.Open();
                return cmd.ExecuteScalar();
            }
            catch (Exception ex)
            {
                //将错误信息写入日志...

                throw ex;
            }
            finally
            {
                conn.Close();
            }
        }
        /// 
        /// 执行结果集查询
        /// 
        /// 
        /// 
        public static SqlDataReader GetReader(string sql)
        {
            SqlConnection conn = new SqlConnection(connString);
            SqlCommand cmd = new SqlCommand(sql, conn);
            try
            {
                conn.Open();
                return cmd.ExecuteReader(CommandBehavior.CloseConnection);
            }
            catch (Exception ex)
            {
                conn.Close();
                //将错误信息写入日志...

                throw ex;
            }
        }
    }
}

2 配置文件的使用

2.1 连接字符串存在的问题

字符串在编译后无法修改。
数据库连接的安全保障_第2张图片

2.2 配置文件的使用

在项目的根目录添加App.config文件。
数据库连接的安全保障_第3张图片

2.3 使用配置文件常见错误

类型初始化设定项引发异常:
数据库连接的安全保障_第4张图片
解决办法:

  • 检查是否已经条件App.config配置文件。
  • 检查用户定义的配置文件“节点名称”和SQLHelper类中的“使用名称是否一致”。

2.4 配置文件总结

关于App.config文件:

  • 程序的配置文件放在应用程序根目录。
  • 属于XML文件。
  • 用途:
    • 保存数据库连接字符串。
    • 保存应用程序常量。

App.config文件使用步骤:

  • 添加App.config。
  • 引用System.Configuration程序集。
  • 引用命名空间System.Configuration。
  • 在App.config定义连接字符串。
  • 在代码中使用连接字符串。

出现错误时:

  • 检查配置文件是否正确添加和定义。
  • 查看定义结点和使用名称是否一致。
  • 配置文件中数据库命名实例需要使用单个"\",而直接在C#代码中需要两个"\\"。

3 字符串的安全问题

当前设置的连接字符串很不安全。
数据库连接的安全保障_第5张图片
解决办法:
数据库连接的安全保障_第6张图片

using System;
using System.Text;
using System.IO;
using System.Security.Cryptography;

namespace StudentManager.Common
{
    /// 
    /// 字符串加密解密类
    /// 
    public sealed class StringSecurity
    {
        private StringSecurity() { }

        #region SHA1 加密

        /// 
        /// 使用SHA1加密字符串。
        /// 
        /// 输入字符串。
        /// 加密后的字符串。(40个字符)
        public static string StringToSHA1Hash(string inputString)
        {
            SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
            byte[] encryptedBytes = sha1.ComputeHash(Encoding.ASCII.GetBytes(inputString));
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < encryptedBytes.Length; i++)
            {
                sb.AppendFormat("{0:x2}", encryptedBytes[i]);
            }
            return sb.ToString();
        }

        #endregion

        #region DES 加密/解密

        private static byte[] key = ASCIIEncoding.ASCII.GetBytes("uiertysd");
        private static byte[] iv = ASCIIEncoding.ASCII.GetBytes("99008855");

        /// 
        /// DES加密。
        /// 
        /// 输入字符串。
        /// 加密后的字符串。
        public static string DESEncrypt(string inputString)
        {
            MemoryStream ms = null;
            CryptoStream cs = null;
            StreamWriter sw = null;

            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            try
            {
                ms = new MemoryStream();
                cs = new CryptoStream(ms, des.CreateEncryptor(key, iv), CryptoStreamMode.Write);
                sw = new StreamWriter(cs);
                sw.Write(inputString);
                sw.Flush();
                cs.FlushFinalBlock();
                return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);
            }
            finally
            {
                if (sw != null) sw.Close();
                if (cs != null) cs.Close();
                if (ms != null) ms.Close();
            }
        }

        /// 
        /// DES解密。
        /// 
        /// 输入字符串。
        /// 解密后的字符串。
        public static string DESDecrypt(string inputString)
        {
            MemoryStream ms = null;
            CryptoStream cs = null;
            StreamReader sr = null;

            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            try
            {
                ms = new MemoryStream(Convert.FromBase64String(inputString));
                cs = new CryptoStream(ms, des.CreateDecryptor(key, iv), CryptoStreamMode.Read);
                sr = new StreamReader(cs);
                return sr.ReadToEnd();
            }
            finally
            {
                if (sr != null) sr.Close();
                if (cs != null) cs.Close();
                if (ms != null) ms.Close();
            }
        }

        #endregion
    }
}

我们先将连接字符串进行加密,配置文件如下:
数据库连接的安全保障_第7张图片
可以采用如下方式使用:
在这里插入图片描述

你可能感兴趣的:(C#)