ASP.NET Core学习历程4

ASP.NET Core加密EF连接字符串

加密字符串呢,其实就是为了使连接隐秘,增强安全性。废话不多说,这篇文章参照 ASP.NET MVC5+EF6+EasyUI 后台管理系统(62)-EF链接串加密 首先呢,创建一个Winform窗体应用程序,需要注意的是需要下载最新版的VS2019才支持Winform窗体应用程序的窗体设计器。下载连接在此奉上不谢!Visual
Studio 2019
Community

在这里插入图片描述

创建AESEncryptHelper类,用来进行加密解密:

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

namespace Apps.EncryptHelper
{
    public class AESEncryptHelper
    {
        /// <summary>
        /// 获取密钥
        /// </summary>
        private static string Key
        {
            get { return @")O[NB]6,YF}+efcaj{+oESb9d8>Z'e9M"; }
        }

        /// <summary>
        /// 256位AES加密
        /// </summary>
        /// <param name="toEncrpy"></param>
        /// <returns></returns>
        public static string Encrypt(string toEncrypt) 
        {
            //256位 AES Key
            byte[] keyArray = UTF8Encoding.UTF8.GetBytes(Key);
            byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);

            RijndaelManaged rDel = new RijndaelManaged();
            rDel.Key = keyArray;
            rDel.Mode = CipherMode.ECB;
            rDel.Padding = PaddingMode.PKCS7;

            ICryptoTransform cTransform = rDel.CreateEncryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }

        /// <summary>
        /// 256位AES解密
        /// </summary>
        /// <param name="toDecrypt"></param>
        /// <returns></returns>
        public static string Decrypt(string toDecrypt)
        {
            //256位 AES Key
            byte[] keyArray = UTF8Encoding.UTF8.GetBytes(Key);
            byte[] toDecryptArray = Convert.FromBase64String(toDecrypt);

            RijndaelManaged rDel = new RijndaelManaged();
            rDel.Key = keyArray;
            rDel.Mode = CipherMode.ECB;
            rDel.Padding = PaddingMode.PKCS7;

            ICryptoTransform cTransform = rDel.CreateDecryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toDecryptArray, 0, toDecryptArray.Length);
            return UTF8Encoding.UTF8.GetString(resultArray);
        }
    }
}

构建布局页面,相当简单:

在这里插入图片描述

直接双击加密和解密两个按钮,生成相应的Onclick事件,

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SNK.EncryptHelper
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 加密字符串
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_Encrypt_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(EncryptStr.Text.Trim()))
            {
                DecryptStr.Text = "对不起,我对加密空数据没有兴趣!";
                return;
            }
            else 
            {
                DecryptStr.Text = AESKeyEncrypt.EncryptKey(EncryptStr.Text);
            }
        }

        /// <summary>
        /// 解密字符串
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_Descrypt_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(EncryptStr.Text.Trim()))
            {
                DecryptStr.Text = "对不起,我对解密空数据不感兴趣!";
                return;
            }
            else if (IsBase64Formtted(EncryptStr.Text))
            {
                DecryptStr.Text = AESKeyEncrypt.DecryptKey(EncryptStr.Text);                
            }
            else 
            {
                DecryptStr.Text = "对不起,我对未加密的数据没兴趣!";
                return;
            }
        }

        /// <summary>
        /// 判断是否为加密过的数据
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static bool IsBase64Formtted(string key)
        {
            try
            {
                //未加密的数据则会抛出异常
                Convert.FromBase64String(key);
                return true;
            }
            catch (Exception)
            {

                return false;
            }
        }
    }
}

将该项目设为启动项目,看运行效果!
在这里插入图片描述

最后,在appsettings.json修改成自己加密的字符串
在这里插入图片描述

在Satrt.cs注入一下即可轻松实现!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using SNK.EncryptHelper;
using SNK.Model.Core;

namespace SNK.Web
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        /// <summary>
        /// 此方法由运行时调用,使用此方法可将服务添加到容器中
        /// </summary>
        public void ConfigureServices(IServiceCollection services)
        {

            //解密数据库的加密连接字符串
            string DBContext = AESKeyEncrypt.DecryptKey(Configuration.GetConnectionString("DBContext"));
            services.AddDbContext<DBContext>(options => options.UseSqlServer(DBContext));//EFCore注入

            //注入自启动
            services.AddControllersWithViews().AddRazorRuntimeCompilation();
        }

        /// <summary>
        /// 此方法由运行时调用,使用此方法配置HTTP请求管道
        /// </summary>
        /// <param name="app"></param>
        /// <param name="env"></param>
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=SNK_Menu}/{action=Index}/{id?}");
            });
        }
    }
}

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页