前端请求参数加密、.NET 后端解密

  • 前端请求参数加密、.NET 后端解密已关闭评论
  • 103 次浏览
  • A+
所属分类:.NET技术
摘要

本文详细介绍了前端请求参数加密、.NET 后端解密,文章较长,请各位看官耐心看完。

本文详细介绍了前端请求参数加密、.NET 后端解密,文章较长,请各位看官耐心看完。

目录

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

1.1、加密解密效果图

前端请求参数加密、.NET 后端解密

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、选择“客户端库”

前端请求参数加密、.NET 后端解密

1.3.2.2、安装下载“CryptoJS”

在“添加客户端库”界面:

  1. 提供程序:选择“unpkg”;
  2. 库:输入“crypto-js@”,进行版本的选择;
  3. 可选择:1、包括所有库文件;2、选择特定文件;

确认无误之后,点击“安装”即可。
前端请求参数加密、.NET 后端解密

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、加密解密效果图

前端请求参数加密、.NET 后端解密

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、选择“客户端库”

前端请求参数加密、.NET 后端解密

2.4.2.2、安装下载“jsencrypt”

在“添加客户端库”界面:

  1. 提供程序:选择“unpkg”;
  2. 库:输入“jsencrypt@”,进行版本的选择;
  3. 可选择:1、包括所有库文件;2、选择特定文件;

确认无误之后,点击“安装”即可。
前端请求参数加密、.NET 后端解密

2.5、安装组件“BouncyCastle”

在菜单栏找到 工具 —> NuGet 包管理器 —> 管理解决方案的NuGet程序包 —> 浏览 —> 搜索 “BouncyCastle” —> 安装。
前端请求参数加密、.NET 后端解密

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>