js传递rsa加密参数给c#后端(密码加密后传到后端)

发布时间 2023-09-20 16:38:09作者: 五官一体即忢

一、前端处理

1、引入js

下载地址:

https://files.cnblogs.com/files/blogs/782924/BigInt.js?t=1695198891&download=true
https://files.cnblogs.com/files/blogs/782924/RSA.js?t=1695198891&download=true
https://files.cnblogs.com/files/blogs/782924/Barrett.js?t=1695198891&download=true

    <script src="../Script/rsa/BigInt.js" type="text/javascript"></script>
    <script src="../Script/rsa/RSA.js" type="text/javascript" ></script>
    <script src="../Script/rsa/Barrett.js" type="text/javascript"></script>

2、调用后端接口获取公钥,对密码进行加密

var password =  $password.val();
$.ajax({
            type: "Post",
            url: "GetRSA.ashx?r=" + Math.random(),
            data: {},
            success: function (Data) {

                var data = JSON.parse(Data);
                var strPublicKeyExponent = data.strPublicKeyExponent;
                var strPublicKeyModulus = data.strPublicKeyModulus;
                setMaxDigits(130);
                var key = new RSAKeyPair(strPublicKeyExponent, "", strPublicKeyModulus);
                var UPWD = encryptedString(key, password);//rsa加密后的密码
              

            },
            error: function (err) {

            }
        });

二、后端处理

1、生成公钥和私钥,每次生成后将私钥存入session

 /// <summary>
    /// GetRSA 的摘要说明    使用session时必须实现IRequiresSessionState
    /// </summary>
public class GetRSA : IHttpHandler,IRequiresSessionState
    {

        /// <summary>
        /// 生成并获取公钥,私钥存入session
        /// </summary>
        /// <param name="context"></param>
        public void ProcessRequest(HttpContext context)
        {
            var ht = RsaEncodeHelper.GetPublickKey(context, "user_login_private_key");//生成公钥并将私钥存入session,key必须与后面解密时的key一致
            context.Response.Write(JsonHelper.Serialize(ht));
        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace StrongSoftManage.Common
{
    /// <summary>
    /// 前后端参数传递rsa加密帮助类
    /// 这里有用到session,外部调用接口必须实现接口IRequiresSessionState,否则会报null异常
    /// </summary>
    public class RsaEncodeHelper
    {

        /// <summary>
        /// 生成公私钥
        /// </summary>
        /// <param name="context"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static Hashtable  GetPublickKey(HttpContext context,string key="")
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            SessionHelper.SetSession(key, rsa.ToXmlString(true));
            //把公钥适当转换,准备发往客户端
            RSAParameters parameter = rsa.ExportParameters(true);
            string strPublicKeyExponent = BytesToHexString(parameter.Exponent);
            string strPublicKeyModulus = BytesToHexString(parameter.Modulus);
            Hashtable ht = new Hashtable();
            ht.Add("strPublicKeyExponent", strPublicKeyExponent);
            ht.Add("strPublicKeyModulus", strPublicKeyModulus);
            return ht;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="word"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetTrueWord(string word, string key = ""){
            try
            {
                RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                string pk = (string)SessionHelper.GetSession(key);
                rsa.FromXmlString(pk);
                byte[] result = rsa.Decrypt(HexStringToBytes(word), false);
                ASCIIEncoding enc = new ASCIIEncoding();
                string truePassWord = enc.GetString(result);
                return truePassWord;
            }
            catch (Exception ex)
            {
                return "";
            }
        }

        public static string BytesToHexString(byte[] input) {
            StringBuilder hexString = new StringBuilder(64);
            for (int i = 0; i < input.Length; i++){
                hexString.Append(String.Format("{0:X2}", input[i]));
            }
            return hexString.ToString();
        }

        public static byte[] HexStringToBytes(string hex)
        {
            if (hex.Length == 0){
                return new byte[] { 0 };
            }

            if (hex.Length % 2 == 1){
                hex = "0" + hex;
            }

            byte[] result = new byte[hex.Length / 2];

            for (int i = 0; i < hex.Length / 2; i++){
                result[i] = byte.Parse(hex.Substring(2 * i, 2), System.Globalization.NumberStyles.AllowHexSpecifier);
            }

            return result;
        }

      
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Channels;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace StrongSoftManage.Common
{
    /// <summary>
    /// Session 操作类
    /// 1、GetSession(string name)根据session名获取session对象
    /// 2、SetSession(string name, object val)设置session
    /// 3、外部调用接口必须实现接口IRequiresSessionState,否则会报null异常
    /// </summary>
    public class SessionHelper
    {
        /// <summary>
        /// 根据session名获取session对象
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static object GetSession(string name)
        {
            return HttpContext.Current.Session[name];
        }
        /// <summary>
        /// 设置session
        /// </summary>
        /// <param name="name">session 名</param>
        /// <param name="val">session 值</param>
        public static void SetSession(string name, object val)
        {
            HttpContext.Current.Session.Remove(name);
            HttpContext.Current.Session.Add(name, val);
        }

        /// <summary>
        /// 清空所有的Session
        /// </summary>
        /// <returns></returns>
        public static void ClearSession()
        {
            HttpContext.Current.Session.Clear();
        }

        /// <summary>
        /// 删除一个指定的ession
        /// </summary>
        /// <param name="name">Session名称</param>
        /// <returns></returns>
        public static void RemoveSession(string name)
        {
            HttpContext.Current.Session.Remove(name);
        }

        /// <summary>
        /// 删除所有的ession
        /// </summary>
        /// <returns></returns>
        public static void RemoveAllSession(string name)
        {
            HttpContext.Current.Session.RemoveAll();
        }
    }
}

2、参数传到后端后解密

            string passWordEncode = context.Request.Form["passWord"];//加密后的密码
            string passWord = RsaEncodeHelper.GetTrueWord(passWordEncode, "user_login_private_key");//解密密码