.Net Core數據庫鏈接字符串加密


1.加密解密方法:創建一個新的靜態類

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;
using System.IO;

namespace ConsoleApp1
{
    public static class AESKeyEncrypt
    {
        #region 加解密方法二(Sha256和Sha512)
        /// <summary>
        /// Creates a SHA256 hash of the specified input.
        /// </summary>
        /// <param name="input">The input.</param>
        /// <returns>A hash</returns>
        public static string Sha256(this string input)
        {
            if (String.IsNullOrEmpty(input)) return string.Empty;
            using (var sha = SHA256.Create())
            {
                var bytes = Encoding.UTF8.GetBytes(input);
                var hash = sha.ComputeHash(bytes);
                return Convert.ToBase64String(hash);
            }
        }
        /// <summary>
        /// Creates a SHA256 hash of the specified input.
        /// </summary>
        /// <param name="input">The input.</param>
        /// <returns>A hash.</returns>
        public static byte[] Sha256(this byte[] input)
        {
            if (input == null)
            {
                return null;
            }
            using (var sha = SHA256.Create())
            {
                return sha.ComputeHash(input);
            }
        }
        /// <summary>
        /// Creates a SHA512 hash of the specified input.
        /// </summary>
        /// <param name="input">The input.</param>
        /// <returns>A hash</returns>
        public static string Sha512(this string input)
        {
            if (string.IsNullOrEmpty(input)) return string.Empty;
            using (var sha = SHA512.Create())
            {
                var bytes = Encoding.UTF8.GetBytes(input);
                var hash = sha.ComputeHash(bytes);
                return Convert.ToBase64String(hash);
            }
        }
        #endregion

        #region 加密解密法一
        //默認密鑰向量 
        private static byte[] Keys = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F };

        /// <summary> 
        /// DES加密字符串 
        /// </summary> 
        /// <param name="encryptString">待加密的字符串</param> 
        /// <param name="encryptKey">加密密鑰,要求為16位</param> 
        /// <returns>加密成功返回加密后的字符串,失敗返回源串</returns> 

        public static string EncryptDES(string encryptString, string encryptKey = "Key123Ace#321Key")
        {
            try
            {
                byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 16));
                byte[] rgbIV = Keys;
                byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
                var DCSP = Aes.Create();
                MemoryStream mStream = new MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Convert.ToBase64String(mStream.ToArray());
            }
            catch (Exception ex)
            {
                return ex.Message + encryptString;
            }

        }

        /// <summary> 
        /// DES解密字符串 
        /// </summary> 
        /// <param name="decryptString">待解密的字符串</param> 
        /// <param name="decryptKey">解密密鑰,要求為16位,和加密密鑰相同</param> 
        /// <returns>解密成功返回解密后的字符串,失敗返源串</returns> 

        public static string DecryptDES(string decryptString, string decryptKey = "Key123Ace#321Key")
        {
            try
            {
                byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey.Substring(0, 16));
                byte[] rgbIV = Keys;
                byte[] inputByteArray = Convert.FromBase64String(decryptString);
                var DCSP = Aes.Create();
                MemoryStream mStream = new MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                Byte[] inputByteArrays = new byte[inputByteArray.Length];
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Encoding.UTF8.GetString(mStream.ToArray());
            }
            catch (Exception ex)
            {
                return ex.Message + decryptString;
            }

        }
        #endregion
    }
}

2.在創建一個控制台應用程序來得到加密的字符串

using System;

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            
        //加密
            string result1 = AESKeyEncrypt.EncryptDES("Data Source=10.31.60.15;Initial Catalog=T_HongShi_3;Persist Security Info=True;User ID=sa;Pwd=123456");
            Console.WriteLine(result1);
        //解密
            string result2 = AESKeyEncrypt.DecryptDES(result1);
            Console.WriteLine(result2);
        }
    }
}

3.將得到的字符串復制到主程序鏈接字符串的位置

  "ConnectionStrings": { "MSSQL": "/Alo3Rq9v/NCKPoiX51T3fsJq3Mp+tZgBZZ1NcoyM0sMpWxyNdBSL/zqSV8dr22eyrXb3oWYfBOxsQibyheovjKyg1zu658fgNga5vbvZN9Nf+LDQibMfuQTuKDfyI6XNSbf6M9utG1UiPjAuCWT+g==" },

4.在Startup類的ConfigureServices方法里注入解密代碼(EF連接字符串使用注入)

#region 解密字符串
            //解密數據庫的加密連接字符串
            string MSSQL = SecurityHelper.DecryptDES(Configuration.GetConnectionString("MSSQL"));
            services.AddDbContext<T_HongShi_3Context>(options => options.UseSqlServer(MSSQL));//EFCore注入

#endregion

5.如果在項目中使用了Dapper還沒有使用DapperHelper那就要再寫一個類來為字符串解碼

using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Hong.Common.Encryption
{
    public  class SecurityStatic
    {
        private readonly IConfiguration Configuration;
        public SecurityStatic(IConfiguration configuration)
        {
            Configuration = configuration;
          
        }

        public string Securityinfo() {
            var SMSSQL = Configuration.GetConnectionString("MSSQL");
            string MSSQL = SecurityHelper.DecryptDES(SMSSQL);
            return MSSQL;
        }

    }
}

然后在構造器里注入此類

//注入解密SQL連接字符串類
        private readonly SecurityStatic _securityStatic;
public ContractRepository(SecurityStatic securityStatic)
        {
            _securityStatic = securityStatic;
        }
public List<ViewContracratetInfo> GetContractLists(string id)
        {
            using (IDbConnection conn = new SqlConnection(_securityStatic.Securityinfo()))
            {
                var q = conn.Query<ViewContracratetInfo>(sql).ToList();
                return q;
            }
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM