前端請求參數加密、.NET 後端解密

来源:https://www.cnblogs.com/lucasDC/archive/2023/09/17/17707813.html
-Advertisement-
Play Games

本文詳細介紹了前端請求參數加密、.NET 後端解密,文章較長,請各位看官耐心看完。 目錄一、前端使用“CryptoJS”,前端AES加密,.NET後端AES解密1.1、加密解密效果圖1.2、CryptoJS介紹1.3、準備工作:安裝“CryptoJS”1.3.1、使用npm進行安裝1.3.2、Vis ...


本文詳細介紹了前端請求參數加密、.NET 後端解密,文章較長,請各位看官耐心看完。

目錄

一、前端使用“CryptoJS”,前端AES加密,.NET後端AES解密

1.1、加密解密效果圖

前端加密,後端解密效果圖

1.2、CryptoJS介紹

CryptoJS是一個JavaScript的加解密的工具包。它支持多種的演算法:MD5、SHA1、SHA2、SHA3、RIPEMD-160 哈希散列,進行 AES、DES、Rabbit、RC4、Triple DES 加解密。

1.3、準備工作:安裝“CryptoJS”

1.3.1、使用npm進行安裝

npm安裝命令如下:

npm install crypto-js --save-dev

1.3.2、Visual Studio中安裝

1.3.2.1、選擇“客戶端庫”

選擇“客戶端庫”

1.3.2.2、安裝下載“CryptoJS”

在“添加客戶端庫”界面:

  1. 提供程式:選擇“unpkg”;
  2. 庫:輸入“crypto-js@”,進行版本的選擇;
  3. 可選擇:1、包括所有庫文件;2、選擇特定文件;

確認無誤之後,點擊“安裝”即可。
安裝“crypto-js”

1.4、H5頁面代碼中引用“crypto-js”

1.5、前端頁面代碼

1.5.1、Html代碼

H5代碼使用了Layui開原框架

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>sometext</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <script src="/lib/jquery/dist/jquery.js"></script>
    <script src="/lib/layui/dist/layui.js"></script>
    <script src="/lib/bootstrap/dist/js/bootstrap.js"></script>
	<script src="/lib/crypto-js/crypto-js.js"></script>
    <link href="/lib/layui/dist/css/layui.css" rel="stylesheet" />
    <link href="/lib/bootstrap/dist/css/bootstrap.css" rel="stylesheet" />
    <style type="text/css"></style>
</head>
<body>
    <div class="wrapper">
        <div class="input-group mb-3">
            <div class="input-group-prepend">
                <span class="input-group-text" id="basic-addon1">脫敏/加密前的內容:</span>
            </div>
            <input type="password" class="form-control" id="sourctText" placeholder="脫敏/加密前的內容" aria-label="sourctText" aria-describedby="basic-addon1">
        </div>
        <br />
        <div class="input-group mb-3">
            <div class="input-group-prepend">
                <span class="input-group-text" id="basic-addon1">加密後的內容:</span>
            </div>
            <input type="text" class="form-control" id="encryptText" placeholder="加密後的內容" readonly="readonly" aria-label="encryptText" aria-describedby="basic-addon1">
        </div>
        <br />
        <div class="input-group mb-3">
            <div class="input-group-prepend">
                <span class="input-group-text" id="basic-addon1">脫敏/加密後的內容:</span>
            </div>
            <input type="text" class="form-control" id="resText" placeholder="脫敏/加密後的內容" readonly="readonly" aria-label="resText" aria-describedby="basic-addon1">
        </div>

        <div class="input-group mb-3">
            <button id="submit" type="button" class="btn btn-primary btn-lg btn-block">提交</button>
        </div>
    </div>
</body>
</html>

1.5.2、javascript代碼

說明:CBC模式前、後端需要確定偏移量的值,並且保持一致,這樣才能確保後端解密成功。

<script type="text/javascript">
    const KEY = CryptoJS.enc.Utf8.parse("lucasnetLUCASNET"); //16位
    const IV = CryptoJS.enc.Utf8.parse("lucasnetLUCASNET");
    layui.use(['form'], function () {
        let form = layui.form;
        $("#submit").on("click", function () {
            let sourctText = $("#sourctText").val();
            if (sourctText != "" && sourctText != null) {
                let encryptText = wordEncrypt(sourctText);
                $("#encryptText").val(encryptText);
                login(encryptText);
            } else {
                layui.layer.alert("密碼為空!", { icon: 5, title: "溫馨提示", closeBtn: 0 });
            }
        });

        function login(sourctText) {
            var word_Encrypt = $.ajax({
                url: "/Home/word_Encrypt",//請求後端介面的路徑
                dataType: "JSON",
                type: "POST",
                data: {
                    "ciphertextpwd": sourctText,
                },
                success: function (res) {
                    let resCode = res.code;
                    let resMsg = res.msg;
                    if ((resCode == "210" || resCode == 210) || (resCode == 220 || resCode == "220") || (resCode == 230 || resCode == "230") || (resCode == 240 || resCode == "240") || (resCode == 260 || resCode == "260")) {
                        //返回數據後關閉loading
                        layer.closeAll();
                        // 在 2 秒鐘後取消 AJAX 請求
                        setTimeout(function () {
                            word_Encrypt.abort(); // 刪除 AJAX 請求
                        }, 2000);
                        layui.layer.alert(resMsg, { icon: 5, title: "溫馨提示", closeBtn: 0 });
                    } else if (resCode == 200 || resCode == "200") {
                        $("#resText").val(resMsg);
                        //返回數據後關閉loading
                        layer.closeAll();
                        // 在 2 秒鐘後取消 AJAX 請求
                        setTimeout(function () {
                            word_Encrypt.abort(); // 刪除 AJAX 請求
                        }, 2000);
                    }
                },
                error: function (error) {
                    //返回數據後關閉loading
                    layer.closeAll();
                    // 在 2 秒鐘後取消 AJAX 請求
                    setTimeout(function () {
                        word_Encrypt.abort(); // 刪除 AJAX 請求
                    }, 2000);
                    layui.layer.alert(error, { icon: 5, title: "溫馨提示", closeBtn: 0 });
                }
            });
        }

        /**
         * 前端AES使用CBC加密 key,iv長度為16位,可相同 自定義即可
         */
        function wordEncrypt(word) {
            let key = KEY;
            let iv = IV;
            let encrypted = "";
            if (typeof word == "string") {
                let srcs = CryptoJS.enc.Utf8.parse(word);
                encrypted = CryptoJS.AES.encrypt(srcs, key, {
                    iv: iv,
                    mode: CryptoJS.mode.CBC,
                    padding: CryptoJS.pad.Pkcs7
                });
            } else if (typeof word == "object") {
                //對象格式的轉成json字元串
                let data = JSON.stringify(word);
                let srcs = CryptoJS.enc.Utf8.parse(data);
                encrypted = CryptoJS.AES.encrypt(srcs, key, {
                    iv: iv,
                    mode: CryptoJS.mode.CBC,
                    padding: CryptoJS.pad.Pkcs7
                });
            }
            return CryptoJS.enc.Base64.stringify(encrypted.ciphertext);
        }
    });
</script>

1.6、.NET 後端代碼

1.6.1、定義公共的密匙欄位

/// <summary>
/// //AES加密所需16位密匙
/// </summary>
private static readonly String strAesKey = "lucasnetLUCASNET";

/// <summary>
/// AES加密所需16位密匙向量
/// </summary>
private static readonly String strAesIv = "lucasnetLUCASNET";

1.6.2、封裝AES解密方法

/// <summary>
///  AES 解密
/// </summary>
/// <param name="str">密文(待解密)</param>
/// <returns></returns>
public string AesDecrypt(string str)
{
    if (string.IsNullOrEmpty(str)) return null;
    Byte[] toEncryptArray = Convert.FromBase64String(str);
    using (RijndaelManaged rm = new RijndaelManaged())
    {
        rm.Key = Encoding.UTF8.GetBytes(strAesKey);
        rm.IV = Encoding.UTF8.GetBytes(strAesIv);
        rm.Mode = CipherMode.CBC;
        rm.Padding = PaddingMode.PKCS7;
        rm.FeedbackSize = 128;
        ICryptoTransform encryptor = rm.CreateDecryptor(rm.Key, rm.IV);
        Byte[] resultArray = encryptor.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
        return Encoding.UTF8.GetString(resultArray);
    }
}

1.6.3、編寫API介面

/// <summary>
/// 解密介面
/// </summary>
/// <param name="ciphertextpwd">密碼密文(待解密)</param>
/// <param name="publicKey">公鑰</param>
/// <param name="privateKey">私鑰</param>
/// <returns></returns>
[HttpPost]
public IActionResult word_Encrypt(string ciphertextpwd)
{
    string resPwd = "";
    try
    {
        resPwd = AesDecrypt(ciphertextpwd);
        return Json(new { code = 200, msg = resPwd });
    }
    catch (Exception ex)
    {
        return Json(new { code = 220, msg = "AES解密時出現錯誤!!!" });
    }
}

二、前端使用“JSEncrypt”,進行非對稱RSA加密,.NET後端解密

2.1、加密解密效果圖

RSA加密解密效果圖

2.2、非對稱加密

所謂的非對稱,即加密和解密用的不是同一個秘鑰。比如用公鑰加密,就要用私鑰解密。非對稱加密的安全性是要好於對稱加密的,但是性能就比較差了。

2.3、RSA

非對稱加密演算法中常用的就是 RSA 了。它是由在 MIT 工作的 3 個人於 1977 年提出,RSA 這個名字的由來便是取自他們 3 人的姓氏首字母。我們在訪問 github 等遠程 git 倉庫時,如果是使用 SSH 協議,需要生成一對公私秘鑰,就可以使用 RSA 演算法。

2.4、準備工作:安裝“jsencrypt”

2.4.1、使用npm進行安裝

npm安裝命令如下:

npm install jsencrypt

2.4.2、Visual Studio中安裝

2.4.2.1、選擇“客戶端庫”

選擇“客戶端庫”

2.4.2.2、安裝下載“jsencrypt”

在“添加客戶端庫”界面:

  1. 提供程式:選擇“unpkg”;
  2. 庫:輸入“jsencrypt@”,進行版本的選擇;
  3. 可選擇:1、包括所有庫文件;2、選擇特定文件;

確認無誤之後,點擊“安裝”即可。
安裝“jsencrypt”

2.5、安裝組件“BouncyCastle”

在菜單欄找到 工具 —> NuGet 包管理器 —> 管理解決方案的NuGet程式包 —> 瀏覽 —> 搜索 “BouncyCastle” —> 安裝。
安裝組件“BouncyCastle”

2.5.1、新建幫助類

2.5.1.1、添加C# RAS生成.NET公鑰與私鑰以及.NET公鑰與私鑰轉Java公鑰私鑰類“RASKeyConversion”

可根據自己需求刪除生成Java的

using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.X509;
using System;
using System.Security.Cryptography;
using System.Xml;

namespace WebApplication1
{
    /// <summary>
    /// C# RAS生成.NET公鑰與私鑰以及.NET公鑰與私鑰轉Java公鑰私鑰類
    /// </summary>
    public class RASKeyConversion
    {
        /// <summary>
        /// 第一個:C# 私鑰;第二個:C# 公鑰;第三個:JAVA私鑰;第四個:JAVA公鑰
        /// </summary>
        private static string[] sKeys = new String[4];

        /// <summary>
        /// 生成公鑰與私鑰方法
        /// </summary>
        /// <returns>第一個:C# 私鑰;第二個:C# 公鑰;第三個:JAVA私鑰;第四個:JAVA公鑰</returns>
        public static string[] createPulbicKey(int size = 1024)
        {
            try
            {
                //密鑰格式要生成pkcs#1格式的  而不是pkcs#8格式的
                using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(size))
                {
                    //C# 私鑰
                    sKeys[0] = rsa.ToXmlString(true);
                    //C# 公鑰
                    sKeys[1] = rsa.ToXmlString(false);
                    //JAVA私鑰
                    sKeys[2] = RSAPrivateKeyDotNet2Java(sKeys[0]);
                    //JAVA公鑰
                    sKeys[3] = RSAPublicKeyDotNet2Java(sKeys[1]);
                    return sKeys;
                }
            }
            catch (Exception)
            {
                return null;
            }
        }

        /// <summary>    
        /// RSA私鑰格式轉換,.net->java    
        /// </summary>    
        /// <param name="privateKey">.net生成的私鑰</param>    
        /// <returns></returns>    
        public static string RSAPrivateKeyDotNet2Java(string privateKey)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(privateKey);
            BigInteger m = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Modulus")[0].InnerText));
            BigInteger exp = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Exponent")[0].InnerText));
            BigInteger d = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("D")[0].InnerText));
            BigInteger p = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("P")[0].InnerText));
            BigInteger q = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Q")[0].InnerText));
            BigInteger dp = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DP")[0].InnerText));
            BigInteger dq = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DQ")[0].InnerText));
            BigInteger qinv = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("InverseQ")[0].InnerText));
            RsaPrivateCrtKeyParameters privateKeyParam = new RsaPrivateCrtKeyParameters(m, exp, d, p, q, dp, dq, qinv);

            PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKeyParam);
            byte[] serializedPrivateBytes = privateKeyInfo.ToAsn1Object().GetEncoded();
            return Convert.ToBase64String(serializedPrivateBytes);
        }

        /// <summary>    
        /// RSA公鑰格式轉換,.net->java    
        /// </summary>    
        /// <param name="publicKey">.net生成的公鑰</param>    
        /// <returns></returns>    
        public static string RSAPublicKeyDotNet2Java(string publicKey)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(publicKey);
            BigInteger m = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Modulus")[0].InnerText));
            BigInteger p = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Exponent")[0].InnerText));
            RsaKeyParameters pub = new RsaKeyParameters(false, m, p);

            SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pub);
            byte[] serializedPublicBytes = publicKeyInfo.ToAsn1Object().GetDerEncoded();
            return Convert.ToBase64String(serializedPublicBytes);
        }
    }
}

2.5.1.2、添加RSA秘鑰轉換幫助類“RsaKeyConvert”

using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Security;
using System.Xml.Linq;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Math;

namespace WebApplication1 //命名空間依據自己的項目進行修改
{
    /// <summary>
    /// RSA秘鑰轉換幫助類
    /// </summary>
    public class RsaKeyConvert
    {

        #region 其他格式的RSA秘鑰轉XML格式秘鑰

        /// <summary>
        /// pem格式的RSA公鑰字元串轉XML格式公鑰 Public Key Convert pem->xml
        /// </summary>
        /// <param name="publicKey">公鑰字元串</param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public static string PublicKeyPemToXml(string publicKey)
        {
            publicKey = PublicKeyFormat(publicKey);
            RsaKeyParameters rsaKeyParameters = new PemReader(new StringReader(publicKey)).ReadObject() as RsaKeyParameters;
            if (rsaKeyParameters == null)
            {
                throw new Exception("Public key format is incorrect");
            }

            XElement xElement = new XElement((XName?)"RSAKeyValue");
            XElement content = new XElement((XName?)"Modulus", Convert.ToBase64String(rsaKeyParameters.Modulus.ToByteArrayUnsigned()));
            XElement content2 = new XElement((XName?)"Exponent", Convert.ToBase64String(rsaKeyParameters.Exponent.ToByteArrayUnsigned()));
            xElement.Add(content);
            xElement.Add(content2);
            return xElement.ToString();
        }

        /// <summary>
        /// Pkcs1格式私鑰轉成Xml Pkcs1->xml
        /// </summary>
        /// <param name="privateKey">Pkcs1格式私鑰字元串</param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public static string PrivateKeyPkcs1ToXml(string privateKey)
        {
            privateKey = Pkcs1PrivateKeyFormat(privateKey);
            RsaPrivateCrtKeyParameters rsaPrivateCrtKeyParameters = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(PrivateKeyInfoFactory.CreatePrivateKeyInfo(((new PemReader(new StringReader(privateKey)).ReadObject() as AsymmetricCipherKeyPair) ?? throw new Exception("Private key format is incorrect")).Private));
            XElement xElement = new XElement((XName?)"RSAKeyValue");
            XElement content = new XElement((XName?)"Modulus", Convert.ToBase64String(rsaPrivateCrtKeyParameters.Modulus.ToByteArrayUnsigned()));
            XElement content2 = new XElement((XName?)"Exponent", Convert.ToBase64String(rsaPrivateCrtKeyParameters.PublicExponent.ToByteArrayUnsigned()));
            XElement content3 = new XElement((XName?)"P", Convert.ToBase64String(rsaPrivateCrtKeyParameters.P.ToByteArrayUnsigned()));
            XElement content4 = new XElement((XName?)"Q", Convert.ToBase64String(rsaPrivateCrtKeyParameters.Q.ToByteArrayUnsigned()));
            XElement content5 = new XElement((XName?)"DP", Convert.ToBase64String(rsaPrivateCrtKeyParameters.DP.ToByteArrayUnsigned()));
            XElement content6 = new XElement((XName?)"DQ", Convert.ToBase64String(rsaPrivateCrtKeyParameters.DQ.ToByteArrayUnsigned()));
            XElement content7 = new XElement((XName?)"InverseQ", Convert.ToBase64String(rsaPrivateCrtKeyParameters.QInv.ToByteArrayUnsigned()));
            XElement content8 = new XElement((XName?)"D", Convert.ToBase64String(rsaPrivateCrtKeyParameters.Exponent.ToByteArrayUnsigned()));
            xElement.Add(content);
            xElement.Add(content2);
            xElement.Add(content3);
            xElement.Add(content4);
            xElement.Add(content5);
            xElement.Add(content6);
            xElement.Add(content7);
            xElement.Add(content8);
            return xElement.ToString();
        }

        /// <summary>
        /// 格式化公鑰字元串
        /// </summary>
        /// <param name="str">公鑰字元串</param>
        /// <returns></returns>
        public static string PublicKeyFormat(string str)
        {
            if (str.StartsWith("-----BEGIN PUBLIC KEY-----"))
            {
                return str;
            }

            List<string> list = new List<string>();
            list.Add("-----BEGIN PUBLIC KEY-----");
            int num;
            for (int i = 0; i < str.Length; i += num)
            {
                num = ((str.Length - i < 64) ? (str.Length - i) : 64);
                list.Add(str.Substring(i, num));
            }

            list.Add("-----END PUBLIC KEY-----");
            return string.Join(Environment.NewLine, list);
        }

        /// <summary>
        /// 格式化Pkcs1私鑰
        /// </summary>
        /// <param name="str">私鑰字元串</param>
        /// <returns></returns>
        public static string Pkcs1PrivateKeyFormat(string str)
        {
            if (str.StartsWith("-----BEGIN RSA PRIVATE KEY-----"))
            {
                return str;
            }

            List<string> list = new List<string>();
            list.Add("-----BEGIN RSA PRIVATE KEY-----");
            int num;
            for (int i = 0; i < str.Length; i += num)
            {
                num = ((str.Length - i < 64) ? (str.Length - i) : 64);
                list.Add(str.Substring(i, num));
            }

            list.Add("-----END RSA PRIVATE KEY-----");
            return string.Join(Environment.NewLine, list);
        }

        #endregion

        #region Xml格式的RSA秘鑰轉格式

        /// <summary>
        /// RSA公鑰格式轉換:Xml格式的公鑰轉Pem格式的公鑰 xml->pem
        /// </summary>
        /// <param name="publicKey">Xml公鑰字元串</param>
        /// <returns></returns>
        public static string PublicKeyXmlToPem(string publicKey)
        {
            XElement xElement = XElement.Parse(publicKey);
            XElement xElement2 = xElement.Element((XName?)"Modulus");
            XElement xElement3 = xElement.Element((XName?)"Exponent");
            RsaKeyParameters obj = new RsaKeyParameters(isPrivate: false, new BigInteger(1, Convert.FromBase64String(xElement2.Value)), new BigInteger(1, Convert.FromBase64String(xElement3.Value)));
            StringWriter stringWriter = new StringWriter();
            PemWriter pemWriter = new PemWriter(stringWriter);
            pemWriter.WriteObject(obj);
            pemWriter.Writer.Close();
            return stringWriter.ToString();
        }

        /// <summary>
        /// RSA私鑰格式轉換:Xml格式的私鑰轉Pkcs1格式的私鑰 xml->Pkcs1
        /// </summary>
        /// <param name="privateKey">Xml私鑰字元串</param>
        /// <returns></returns>
        public static string PrivateKeyXmlToPkcs1(string privateKey)
        {
            XElement xElement = XElement.Parse(privateKey);
            XElement xElement2 = xElement.Element((XName?)"Modulus");
            XElement xElement3 = xElement.Element((XName?)"Exponent");
            XElement xElement4 = xElement.Element((XName?)"P");
            XElement xElement5 = xElement.Element((XName?)"Q");
            XElement xElement6 = xElement.Element((XName?)"DP");
            XElement xElement7 = xElement.Element((XName?)"DQ");
            XElement xElement8 = xElement.Element((XName?)"InverseQ");
            XElement xElement9 = xElement.Element((XName?)"D");
            RsaPrivateCrtKeyParameters obj = new RsaPrivateCrtKeyParameters(new BigInteger(1, Convert.FromBase64String(xElement2.Value)), new BigInteger(1, Convert.FromBase64String(xElement3.Value)), new BigInteger(1, Convert.FromBase64String(xElement9.Value)), new BigInteger(1, Convert.FromBase64String(xElement4.Value)), new BigInteger(1, Convert.FromBase64String(xElement5.Value)), new BigInteger(1, Convert.FromBase64String(xElement6.Value)), new BigInteger(1, Convert.FromBase64String(xElement7.Value)), new BigInteger(1, Convert.FromBase64String(xElement8.Value)));
            StringWriter stringWriter = new StringWriter();
            PemWriter pemWriter = new PemWriter(stringWriter);
            pemWriter.WriteObject(obj);
            pemWriter.Writer.Close();
            return stringWriter.ToString();
        }

        #endregion

    }
}

2.5.1.3、添加RSA加密幫助類“RSACrypto”

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

namespace WebApplication1 //命名空間依據自己的項目進行修改
{
    /// <summary>
    /// RSA加密幫助類
    /// </summary>
    public class RSACrypto
    {
        /// <summary>
        /// 預設的私鑰
        /// </summary>
        private const string defaultprivateKey = @"MIICXAIBAAKBgQCC0hrRIjb3noDWNtbDpANbjt5Iwu2NFeDwU16Ec87ToqeoIm2KI+cOs81JP9aTDk/jkAlU97mN8wZkEMDr5utAZtMVht7GLX33Wx9XjqxUsDfsGkqNL8dXJklWDu9Zh80Ui2Ug+340d5dZtKtd+nv09QZqGjdnSp9PTfFDBY133QIDAQABAoGAJBNTOITaP6LCyKVKyEdnHaKNAz0DS+V9UwjKhyAgfcAxwm3sDdd6FQCEW0TIJA7Np7rFYrGwcR1UOoKxkNxB10ACl6JX4rE7xKS6NLZumdwxON/KgDb+2SQtWEXDgBySZ7Znv/FhEp1RmoBDjZ05E99kILWO3ToorUM0Eq2GHQkCQQCnUMXgZa4HS0tu
INzysgB37d7ene9+CIARyJphs079qao2UWCgXqen43Ob6GJUgulz7We+4JOZFld0TfEi1E5rAkEAyClQAVzafLO3gXgqH7tbRbPPx788+4opxT9QBo2Trzl6/3FlcC1PIZeqbQ/Oc2wT7jmidFnpyTEnM2p7Yq3U1wJBAILTWaX4W3dAnJ5j+9+Y51zfFiEjhRwbMWi2XmB+gAlAHOOUBeXfnWBdLQx/TEOgiUIoI7LQjxhoq8E5II+HSjkCQDlKSdH6B7dFoTJ3eGcYsykiLEiZ3hSJGSeR1Y/qmei/ZQsUI9qVvV56EJeivI6g0puO94ah7Z5eaT/4LFS0OIUCQDgLn586pGgeidLhQsIe/AR3y9YOCAygTFLxzmeBXOKtM90q4516KWlTtK2u99442mNi7hNmjryBVwk62foWo8w=";

        /// <summary>
        /// 預設公鑰
        /// </summary>
        private const string defaultpublicKey = @"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCC0hrRIjb3noDWNtbDpANbjt5Iwu2NFeDwU16Ec87ToqeoIm2KI+cOs81JP9aTDk/jkAlU97mN8wZkEMDr5utAZtMVht7GLX33Wx9XjqxUsDfsGkqNL8dXJklWDu9Zh80Ui2Ug+340d5dZtKtd+nv09QZqGjdnSp9PTfFDBY133QIDAQAB";

        private RSACryptoServiceProvider _privateKeyRsaProvider;
        private RSACryptoServiceProvider _publicKeyRsaProvider;

        /// <summary>
        /// RSA加密幫助類構造函數
        /// </summary>
        /// <param name="privateKey">RSA解密密匙</param>
        /// <param name="publicKey">RSA加密密匙</param>
        public RSACrypto(string privateKey = "", string publicKey = "")
        {
            //判斷私鑰密匙是否為空,為空,使用預設的私鑰;
            if (string.IsNullOrEmpty(privateKey))
            {
                privateKey = defaultprivateKey;
            }
            //判斷公鑰密匙是否為空,為空,使用預設的公鑰;
            if (string.IsNullOrEmpty(publicKey))
            {
                publicKey = defaultpublicKey;
            }
            //不為空:使用定義的私鑰密匙創建
            if (!string.IsNullOrEmpty(privateKey))
            {
                _privateKeyRsaProvider = CreateRsaProviderFromPrivateKey(privateKey);
            }
            //不為空:使用定義的公鑰密匙創建
            if (!string.IsNullOrEmpty(publicKey))
            {
                _publicKeyRsaProvider = CreateRsaProviderFromPublicKey(publicKey);
            }
        }

        public string GetPublicRsaKeyStr(string publicKey)
        {
            string keyStr = "";
            CreateRsaProviderFromPublicKey(publicKey);
            return keyStr;
        }

        /// <summary>
        /// RSA解密
        /// </summary>
        /// <param name="cipherText">解密的密文字元串</param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public string RSADecrypt(string cipherText)
        {
            if (_privateKeyRsaProvider == null)
            {
                throw new Exception("提供的RSA私鑰為空");
            }
            if (string.IsNullOrEmpty(cipherText))
            {
                return "";
            }
            return Encoding.UTF8.GetString(_privateKeyRsaProvider.Decrypt(System.Convert.FromBase64String(cipherText), false));
        }

        /// <summary>
        /// RSA解密
        /// </summary>
        /// <param name="cipherText">需要解密的密文字元串</param>
        /// <param name="publicKeyString">私鑰</param>
        /// <param name="keyType">密鑰類型XML/PEM</param>
        /// <returns></returns>
        public static string RSADecrypt(string cipherText, string privateKeyString, string keyType, int size = 1024)
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(size);
            switch (keyType)
            {
                case "XML":
                    rsa.FromXmlString(privateKeyString);
                    break;
                case "PEM":
                    break;
                default:
                    throw new Exception("不支持的密鑰類型");
            }
            int MaxBlockSize = rsa.KeySize / 8;    //解密塊最大長度限制
            //正常解密
            if (cipherText.Length <= MaxBlockSize)
            {
                byte[] hashvalueDcy = rsa.Decrypt(System.Convert.FromBase64String(cipherText), false);//解密
                return Encoding.GetEncoding("UTF-8").GetString(hashvalueDcy);
            }
            //分段解密
            else
            {
                using (MemoryStream CrypStream = new MemoryStream(System.Convert.FromBase64String(cipherText)))
                {
                    using (MemoryStream PlaiStream = new MemoryStream())
                    {
                        Byte[] Buffer = new Byte[MaxBlockSize];
                        int BlockSize = CrypStream.Read(Buffer, 0, MaxBlockSize);

                        while (BlockSize > 0)
                        {
                            Byte[] ToDecrypt = new Byte[BlockSize];
                            Array.Copy(Buffer, 0, ToDecrypt, 0, BlockSize);

                            Byte[] Plaintext = rsa.Decrypt(ToDecrypt, false);
                            PlaiStream.Write(Plaintext, 0, Plaintext.Length);
                            BlockSize = CrypStream.Read(Buffer, 0, MaxBlockSize);
                        }
                        string output = Encoding.GetEncoding("UTF-8").GetString(PlaiStream.ToArray());
                        return output;
                    }
                }
            }
        }

        /// <summary>
        /// RSA加密
        /// </summary>
        /// <param name="text">需要進行加密的明文字元串</param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public string RSAEncrypt(string text)
        {
            if (_publicKeyRsaProvider == null)
            {
                throw new Exception("提供的RSA公鑰為空");
            }
            return Convert.ToBase64String(_publicKeyRsaProvider.Encrypt(Encoding.UTF8.GetBytes(text), false));
        }

        /// <summary>
        /// RSA加密
        /// </summary>
        /// <param name="clearText">需要加密的明文字元串</param>
        /// <param name="publicKeyString">公鑰</param>
        /// <param name="keyType">密鑰類型XML/PEM</param>
        /// <returns></returns>
        public static string RSAEncrypt(string clearText, string publicKeyString, string keyType, int size = 1024)
        {
            byte[] data = Encoding.GetEncoding("UTF-8").GetBytes(clearText);
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(size);
            switch (keyType)
            {
                case "XML":
                    rsa.FromXmlString(publicKeyString);
                    break;
                case "PEM":
                    break;
                default:
                    throw new Exception("不支持的密鑰類型");
            }
            //加密塊最大長度限制,如果加密數據的長度超過 秘鑰長度/8-11,會引髮長度不正確的異常,所以進行數據的分塊加密
            int MaxBlockSize = rsa.KeySize / 8 - 11;
            //正常長度
            if (data.Length <= MaxBlockSize)
            {
                byte[] hashvalueEcy = rsa.Encrypt(data, false); //加密
                return System.Convert.ToBase64String(hashvalueEcy);
            }
            //長度超過正常值
            else
            {
                using (MemoryStream PlaiStream = new MemoryStream(data))
                using (MemoryStream CrypStream = new MemoryStream())
                {
                    Byte[] Buffer = new Byte[MaxBlockSize];
                    int BlockSize = PlaiStream.Read(Buffer, 0, MaxBlockSize);
                    while (BlockSize > 0)
                    {
                        Byte[] ToEncrypt = new Byte[BlockSize];
                        Array.Copy(Buffer, 0, ToEncrypt, 0, BlockSize);

                        Byte[] Cryptograph = rsa.Encrypt(ToEncrypt, false);
                        CrypStream.Write(Cryptograph, 0, Cryptograph.Length);
                        BlockSize = PlaiStream.Read(Buffer, 0, MaxBlockSize);
                    }
                    return System.Convert.ToBase64String(CrypStream.ToArray(), Base64FormattingOptions.None);
                }
            }
        }

        /// <summary>
        /// 通過提供的RSA私鑰來創建RSA
        /// </summary>
        /// <param name="privateKey">私鑰字元串</param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        private RSACryptoServiceProvider CreateRsaProviderFromPrivateKey(string privateKey)
        {
            byte[] privateKeyBits = System.Convert.FromBase64String(privateKey);
            RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
            RSAParameters RSAparams = new RSAParameters();
            using (BinaryReader binr = new BinaryReader(new MemoryStream(privateKeyBits)))
            {
                byte bt = 0;
                ushort twobytes = 0;
                twobytes = binr.ReadUInt16();
                if (twobytes == 0x8130)
                {
                    binr.ReadByte();
                }
                else if (twobytes == 0x8230)
                {
                    binr.ReadInt16();
                }
                else
                {
                    throw new Exception("Unexpected value read binr.ReadUInt16()");
                }
                twobytes = binr.ReadUInt16();
                if (twobytes != 0x0102)
                {
                    throw new Exception("Unexpected version");
                }
                bt = binr.ReadByte();
                if (bt != 0x00)
                {
                    throw new Exception("Unexpected value read binr.ReadByte()");
                }
                RSAparams.Modulus = binr.ReadBytes(GetIntegerSize(binr));
                RSAparams.Exponent = binr.ReadBytes(GetIntegerSize(binr));
                RSAparams.D = binr.ReadBytes(GetIntegerSize(binr));
                RSAparams.P = binr.ReadBytes(GetIntegerSize(binr));
                RSAparams.Q = binr.ReadBytes(GetIntegerSize(binr));
                RSAparams.DP = binr.ReadBytes(GetIntegerSize(binr));
                RSAparams.DQ = binr.ReadBytes(GetIntegerSize(binr));
                RSAparams.InverseQ = binr.ReadBytes(GetIntegerSize(binr));
            }
            RSA.ImportParameters(RSAparams);
            return RSA;
        }

        /// <summary>
        /// 獲取整數大小
        /// </summary>
        /// <param name="binr"></param>
        /// <returns></returns>
        private int GetIntegerSize(BinaryReader binr)
        {
            byte bt = 0;
            byte lowbyte = 0x00;
            byte highbyte = 0x00;
            int count = 0;
            bt = binr.ReadByte();
            if (bt != 0x02)
                return 0;
            bt = binr.ReadByte();

            if (bt == 0x81)
                count = binr.ReadByte();
            else
                if (bt == 0x82)
            {
                highbyte = binr.ReadByte();
                lowbyte = binr.ReadByte();
                byte[] modint = { lowbyte, highbyte, 0x00, 0x00 };
                count = BitConverter.ToInt32(modint, 0);
            }
            else
            {
                count = bt;
            }

            while (binr.ReadByte() == 0x00)
            {
                count -= 1;
            }
            binr.BaseStream.Seek(-1, SeekOrigin.Current);
            return count;
        }

        /// <summary>
        /// 通過提供的RSA公鑰來創建RSA
        /// </summary>
        /// <param name="publicKeyString">公鑰字元串</param>
        /// <returns></returns>
        private RSACryptoServiceProvider CreateRsaProviderFromPublicKey(string publicKeyString)
        {
            // encoded OID sequence for  PKCS #1 rsaEncryption szOID_RSA_RSA = "1.2.840.113549.1.1.1"
            byte[] SeqOID = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 };
            byte[] x509key;
            byte[] seq = new byte[15];
            int x509size;

            x509key = Convert.FromBase64String(publicKeyString);
            x509size = x509key.Length;

            // ---------  Set up stream to read the asn.1 encoded SubjectPublicKeyInfo blob  ------
            using (MemoryStream mem = new MemoryStream(x509key))
            {
                using (BinaryReader binr = new BinaryReader(mem))  //wrap Memory Stream with BinaryReader for easy reading
                {
                    byte bt = 0;
                    ushort twobytes = 0;

                    twobytes = binr.ReadUInt16();
                    if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
                        binr.ReadByte();    //advance 1 byte
                    else if (twobytes == 0x8230)
                        binr.ReadInt16();   //advance 2 bytes
                    else
                        return null;

                    seq = binr.ReadBytes(15);       //read the Sequence OID
                    if (!CompareBytearrays(seq, SeqOID))    //make sure Sequence for OID is correct
                        return null;

                    twobytes = binr.ReadUInt16();
                    if (twobytes == 0x8103) //data read as little endian order (actual data order for Bit String is 03 81)
                        binr.ReadByte();    //advance 1 byte
                    else if (twobytes == 0x8203)
                        binr.ReadInt16();   //advance 2 bytes
                    else
                        return null;

                    bt = binr.ReadByte();
                    if (bt != 0x00)     //expect null byte next
                        return null;

                    twobytes = binr.ReadUInt16();
                    if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
                        binr.ReadByte();    //advance 1 byte
                    else if (twobytes == 0x8230)
                        binr.ReadInt16();   //advance 2 bytes
                    else
                        return null;

                    twobytes = binr.ReadUInt16();
                    byte lowbyte = 0x00;
                    byte highbyte = 0x00;

                    if (twobytes == 0x8102) //data read as little endian order (actual data order for Integer is 02 81)
                        lowbyte = binr.ReadByte();  // read next bytes which is bytes in modulus
                    else if (twobytes == 0x8202)
                    {
                        highbyte = binr.ReadByte(); //advance 2 bytes
                        lowbyte = binr.ReadByte();
                    }
                    else
                        return null;
                    byte[] modint = { lowbyte, highbyte, 0x00, 0x00 };   //reverse byte order since asn.1 key uses big endian order
                    int modsize = BitConverter.ToInt32(modint, 0);

                    int firstbyte = binr.PeekChar();
                    if (firstbyte == 0x00)
                    {   //if first byte (highest order) of modulus is zero, don't include it
                        binr.ReadByte();    //skip this null byte
                        modsize -= 1;   //reduce modulus buffer size by 1
                    }

                    byte[] modulus = binr.ReadBytes(modsize);   //讀取模量位元組

                    if (binr.ReadByte() != 0x02)            //期望指數數據為Integer
                        return null;
                    int expbytes = (int)binr.ReadByte();        // should only need one byte for actual exponent data (for all useful values)
                    byte[] exponent = binr.ReadBytes(expbytes);

                    // ------- create RSACryptoServiceProvider instance and initialize with public key -----
                    RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
                    RSAParameters RSAKeyInfo = new RSAParameters();
                    RSAKeyInfo.Modulus = modulus;
                    RSAKeyInfo.Exponent = exponent;
                    RSA.ImportParameters(RSAKeyInfo);
                    return RSA;
                }
            }
        }

        /// <summary>
        /// 比較位元組數組
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <returns></returns>
        private bool CompareBytearrays(byte[] a, byte[] b)
        {
            if (a.Length != b.Length)
            {
                return false;
            }
            int i = 0;
            foreach (byte c in a)
            {
                if (c != b[i])
                {
                    return false;
                }
                i++;
            }
            return true;
        }

    }
}

2.6、.NET 控制器後端代碼

2.6.1、視圖控製圖代碼

public IActionResult worddata()
{
    var dataStr = RASKeyConversion.createPulbicKey();
    publicKey = RsaKeyConvert1.PublicKeyXmlToPem(dataStr[1]);
    privateKey = RsaKeyConvert1.PrivateKeyXmlToPkcs1(dataStr[0]);
    ViewBag.publicKey = publicKey;
    ViewBag.privateKey = privateKey;
    return View();
}

2.6.2、POST請求介面代碼

/// <summary>
/// 解密介面
/// </summary>
/// <param name="pwd"></param>
/// <param name="privateKey">私鑰</param>
/// <returns></returns>
[HttpPost]
public IActionResult wordEncrypt(string pwd, string privateKey)
{
    string resPwd = "";
    try
    {
        string privateStr= RsaKeyConvert1.PrivateKeyPkcs1ToXml(privateKey);
        resPwd = RSACrypto.RSADecrypt(pwd,privateStr,"XML");
        return Json(new { code = 200, msg = resPwd });
    }
    catch (Exception ex)
    {
        return Json(new { code = 220, msg = "RSA解密時出現錯誤!!!" });
    }
}

2.7、前端視圖頁面代碼

2.7.1、Html代碼

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>sometext</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <script src="/lib/jquery/dist/jquery.js"></script>
    <script src="/lib/layui/dist/layui.js"></script>
    <script src="/lib/jsencrypt/bin/jsencrypt.js"></script>
    <script src="/lib/bootstrap/dist/js/bootstrap.js"></script>
    <link href="/lib/layui/dist/css/layui.css" rel="stylesheet" />
    <link href="/lib/bootstrap/dist/css/bootstrap.css" rel="stylesheet" />
    <style type="text/css"></style>
</head>
<body>
    <div class="wrapper">
        <div class="input-group mb-3">
            <div class="input-group-prepend">
                <span class="input-group-text" id="basic-addon1">脫敏/加密前的內容:</span>
            </div>
            <input type="password" class="form-control" id="sourctText" placeholder="脫敏/加密前的內容" aria-label="sourctText" aria-describedby="basic-addon1">
        </div>
        <br />
        <div class="input-group mb-3">
            <div class="input-group-prepend">
                <span class="input-group-text" id="basic-addon1">加密後的內容:</span>
            </div>
            <input type="text" class="form-control" id="encryptText" placeholder="加密後的內容" readonly="readonly" aria-label="encryptText" aria-describedby="basic-addon1">
        </div>
        <input type="hidden" value="@ViewBag.publicKey" id="publicKey" readonly="readonly" />
        <input type="hidden" value="@ViewBag.privateKey" id="privateKey" readonly="readonly" />
        <br />
        <div class="input-group mb-3">
            <div class="input-group-prepend">
                <span class="input-group-text" id="basic-addon1">脫敏/加密後的內容:</span>
            </div>
            <input type="text" class="form-control" id="resText" placeholder="脫敏/加密後的內容" readonly="readonly" aria-label="resText" aria-describedby="basic-addon1">
        </div>

        <div class="input-group mb-3">
            <button id="submit" type="button" class="btn btn-primary btn-lg btn-block">提交</button>
        </div>
    </div>
</body>
</html>

2.7.2、javascript代碼

<script type="text/javascript">
    const encryptor = new JSEncrypt()
    layui.use(['form'], function () {
        let form = layui.form;

        $("#submit").on("click", function () {
            let publicKey = $("#publicKey").val();
            let privateKey = $("#privateKey").val();
            let sourctText = $("#sourctText").val();
            if (sourctText != "" && sourctText != null) {
                encryptor.setPublicKey(publicKey) // 設置公鑰
                let cipherText = encryptor.encrypt(sourctText);
                $("#encryptText").val(cipherText);
                login(cipherText, publicKey, privateKey);
            } else {
                layui.layer.alert("密碼為空!", { icon: 5, title: "溫馨提示", closeBtn: 0 });
            }
        });

        function login(sourctText, publicKey, privateKey) {
            var wordEncrypt= $.ajax({
                url: "/Home/wordEncrypt",//請求後端介面的路徑
                dataType: "JSON",
                type: "POST",
                data: {
                    "pwd": sourctText,
                    //"publicKey": publicKey,
                    "privateKey": privateKey
                },
                success: function (res) {
                    let resCode = res.code;
                    let resMsg = res.msg;
                    if ((resCode == "210" || resCode == 210) || (resCode == 220 || resCode == "220") || (resCode == 230 || resCode == "230") || (resCode == 240 || resCode == "240") || (resCode == 260 || resCode == "260")) {
                        //返回數據後關閉loading
                        layer.closeAll();
                        // 在 2 秒鐘後取消 AJAX 請求
                        setTimeout(function () {
                            wordEncrypt.abort(); // 刪除 AJAX 請求
                        }, 2000);
                        layui.layer.alert(resMsg, { icon: 5, title: "溫馨提示", closeBtn: 0 });
                    } else if (resCode == 200 || resCode == "200") {
                        $("#resText").val(resMsg);
                        //返回數據後關閉loading
                        layer.closeAll();
                        // 在 2 秒鐘後取消 AJAX 請求
                        setTimeout(function () {
                            wordEncrypt.abort(); // 刪除 AJAX 請求
                        }, 2000);
                    }
                },
                error: function (error) {
                    //返回數據後關閉loading
                    layer.closeAll();
                    // 在 2 秒鐘後取消 AJAX 請求
                    setTimeout(function () {
                        wordEncrypt.abort(); // 刪除 AJAX 請求
                    }, 2000);
                    layui.layer.alert(error, { icon: 5, title: "溫馨提示", closeBtn: 0 });
                }
            });
        }
    });
</script>

本文來自博客園,作者:TomLucas,轉載請註明原文鏈接:https://www.cnblogs.com/lucasDC/p/17707813.html


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 目錄 線程簡介 線程實現(重點) 線程狀態 線程同步(重點) 線程通信問題 線程實現: 方式一:繼承Thread類 /** * TODO * @author 清蓮孤舟 * @CreateDate 2023/9/17/9:28 * 創建線程的方式一:通過繼承Thread類實現 */ //繼承Threa ...
  • 什麼是 Prometheus Prometheus 是一個開源的系統監控和警報工具,最初由 SoundCloud 開發,並於 2012 年發佈為開源項目。它是一個非常強大和靈活的工具,用於監控應用程式和系統的性能,並根據預定義的規則觸發警報。以下是對 Prometheus 的詳細介紹: 特點和優勢: ...
  • 寫在前面 上一小節中我們從0到1 使用Vite搭建了一個Vue3項目,並集成了Element Plus 實現了一個簡單的增刪改查頁面。 這一篇中我們將使用IDEA快速搭建一個SpringBoot3.x的項目。 一、創建項目 1、File->new->project 2、選擇“Spring Initi ...
  • 超級好用繪圖工具(Draw.io+Github) 方案簡介 繪圖工具:Draw.io 存儲方式: Github 1 Draw.io 1.2 簡介 ​ 是一款免費開源的線上流程圖繪製軟體,可以用於創建流程圖、組織結構圖、網路圖、UML圖等各種類型的圖表。它提供了豐富的圖形元素和編輯功能,使用戶能夠輕鬆 ...
  • 1. IO模型 記憶體和外設的交互叫做IO,網路IO就是將數據在記憶體和網卡間拷貝。 IO本質就是等待和拷貝,一般等待耗時往往遠高於拷貝耗時。所以提高IO效率就是儘可能減少等待時間的比重。 IO模型 簡單對比解釋 阻塞IO 阻塞等待數據到來 非阻塞IO 輪詢等待數據到來 信號驅動 信號遞達時再來讀取或寫 ...
  • 現代軟體應用很少獨立工作。典型的應用程式會與幾個外部系統進行通信,如: 資料庫、 消息系統、 緩存提供商 其他第三方服務。 你應該編寫測試確保一切正常運行。 單元測試有助於隔離地測試業務邏輯,不涉及任何外部服務。它們易於編寫並提供幾乎即時的反饋。 有了單元測試還不夠,集成測試用來驗證與外部系統的交互 ...
  • 創建C#項目且使用.Net6.0以上的版本時,預設code會使用頂級語句形式: 1、略去static void Main(String[ ] args)主方法入口; 2、隱式使用(即隱藏且根據代碼所需要的類自動調用)其他命名空間(包括): using System; using System.IO; ...
  • 當使用LINQ查詢數據時,我們常常會面臨選擇使用.AsEnumerable(), .AsQueryable(), 和 .ToList()方法的情況。這些方法在使用時有不同的效果和影響,需要根據具體場景來選擇合適的方法 .AsEnumerable()方法: 使用.AsEnumerable()方法可以將 ...
一周排行
    -Advertisement-
    Play Games
  • 前言 微服務架構已經成為搭建高效、可擴展系統的關鍵技術之一,然而,現有許多微服務框架往往過於複雜,使得我們普通開發者難以快速上手並體驗到微服務帶了的便利。為瞭解決這一問題,於是作者精心打造了一款最接地氣的 .NET 微服務框架,幫助我們輕鬆構建和管理微服務應用。 本框架不僅支持 Consul 服務註 ...
  • 先看一下效果吧: 如果不會寫動畫或者懶得寫動畫,就直接交給Blend來做吧; 其實Blend操作起來很簡單,有點類似於在操作PS,我們只需要設置關鍵幀,滑鼠點來點去就可以了,Blend會自動幫我們生成我們想要的動畫效果. 第一步:要創建一個空的WPF項目 第二步:右鍵我們的項目,在最下方有一個,在B ...
  • Prism:框架介紹與安裝 什麼是Prism? Prism是一個用於在 WPF、Xamarin Form、Uno 平臺和 WinUI 中構建鬆散耦合、可維護和可測試的 XAML 應用程式框架 Github https://github.com/PrismLibrary/Prism NuGet htt ...
  • 在WPF中,屏幕上的所有內容,都是通過畫筆(Brush)畫上去的。如按鈕的背景色,邊框,文本框的前景和形狀填充。藉助畫筆,可以繪製頁面上的所有UI對象。不同畫筆具有不同類型的輸出( 如:某些畫筆使用純色繪製區域,其他畫筆使用漸變、圖案、圖像或繪圖)。 ...
  • 前言 嗨,大家好!推薦一個基於 .NET 8 的高併發微服務電商系統,涵蓋了商品、訂單、會員、服務、財務等50多種實用功能。 項目不僅使用了 .NET 8 的最新特性,還集成了AutoFac、DotLiquid、HangFire、Nlog、Jwt、LayUIAdmin、SqlSugar、MySQL、 ...
  • 本文主要介紹攝像頭(相機)如何採集數據,用於類似攝像頭本地顯示軟體,以及流媒體數據傳輸場景如傳屏、視訊會議等。 攝像頭採集有多種方案,如AForge.NET、WPFMediaKit、OpenCvSharp、EmguCv、DirectShow.NET、MediaCaptre(UWP),網上一些文章以及 ...
  • 前言 Seal-Report 是一款.NET 開源報表工具,擁有 1.4K Star。它提供了一個完整的框架,使用 C# 編寫,最新的版本採用的是 .NET 8.0 。 它能夠高效地從各種資料庫或 NoSQL 數據源生成日常報表,並支持執行複雜的報表任務。 其簡單易用的安裝過程和直觀的設計界面,我們 ...
  • 背景需求: 系統需要對接到XXX官方的API,但因此官方對接以及管理都十分嚴格。而本人部門的系統中包含諸多子系統,系統間為了穩定,程式間多數固定Token+特殊驗證進行調用,且後期還要提供給其他兄弟部門系統共同調用。 原則上:每套系統都必須單獨接入到官方,但官方的接入複雜,還要官方指定機構認證的證書 ...
  • 本文介紹下電腦設備關機的情況下如何通過網路喚醒設備,之前電源S狀態 電腦Power電源狀態- 唐宋元明清2188 - 博客園 (cnblogs.com) 有介紹過遠程喚醒設備,後面這倆天瞭解多了點所以單獨加個隨筆 設備關機的情況下,使用網路喚醒的前提條件: 1. 被喚醒設備需要支持這WakeOnL ...
  • 前言 大家好,推薦一個.NET 8.0 為核心,結合前端 Vue 框架,實現了前後端完全分離的設計理念。它不僅提供了強大的基礎功能支持,如許可權管理、代碼生成器等,還通過採用主流技術和最佳實踐,顯著降低了開發難度,加快了項目交付速度。 如果你需要一個高效的開發解決方案,本框架能幫助大家輕鬆應對挑戰,實 ...