iview框架接口参数加密、服务端解密方式

第一、Web端请求时参数加密:
引入加密:

import JSEncrypt from "jsencrypt";
import Qs from 'qs'

package.json:中jsencrypt的版本号:
iview框架接口参数加密、服务端解密方式_第1张图片

iview框架接口参数加密、服务端解密方式_第2张图片
代码:

 request(options) {
        //  options.data = Qs.stringify(options.data);
        //接口参数加密(地址传参加密)     
        var encrypt = new JSEncrypt();
        encrypt.setPublicKey(
            "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDmb2bXhcfeiosnxs0bD17isalelyS2/0xKQdJUVUyMdt+/5Inm/S5upDFrliMs3i9zj3PtJWO7yzRfiBnoDNlOfTqPNY6DI9FXnhDgjQMJhp1Zbhl7d74E63CBVTU6Deocqfy/KCiPjQnpTzln89Mm7eE3WbvlmvX3mO7uD2/geQIDAQAB"
        );
        if (options.params) {
            options.params = encrypt.encrypt(Qs.stringify(options.params));
        }
        const instance = axios.create()
        options = Object.assign(this.getInsideConfig(), options)
        this.interceptors(instance, options.url)
        return instance(options)
    }

第二、服务端解密:
项目结构:
iview框架接口参数加密、服务端解密方式_第3张图片
1、创建解密类文件CustomerMessageProcesssingHandler.cs
iview框架接口参数加密、服务端解密方式_第4张图片

代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web;

namespace Web.App_Start
{
    public class CustomerMessageProcesssingHandler : MessageProcessingHandler
    {
        public static string RSADecrypt(string privateKey, string content)
        {
            try
            {
                RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                byte[] cipherBytes;
                rsa.FromXmlString(privateKey);
                cipherBytes = rsa.Decrypt(Convert.FromBase64String(content), false);
                rsa.Dispose();

                return Encoding.UTF8.GetString(cipherBytes);
            }
            catch (Exception)
            {
                return content;
            }
        }
        /// 
        /// 解密Url请求
        /// 
        /// 
        /// 
        /// 
        protected override HttpRequestMessage ProcessRequest(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (request.Method == HttpMethod.Options)
            {
                return request;
            }

            if (request.RequestUri.AbsolutePath.Contains("GetOAuthForUserInfo"))
            {
                return request;
            }
            var contentType = request.Content.Headers.ContentType;

            //获取私钥
            //string privateKey = Encoding.UTF8.GetString(Convert.FromBase64String(CommonMethod.GetPrivateKey()));
            string privateKey = "5m9m14XH3oqLJ8bNGw9e4rGpXpcktv9MSkHSVFVMjHbfv+SJ5v0ubqQxa5YjLN4vc49z7SVju8s0X4gZ6AzZTn06jzWOgyPRV54Q4I0DCYadWW4Ze3e+BOtwgVU1Og3qHKn8vygoj40J6U85Z/PTJu3hN1m75Zr195ju7g9v4Hk=AQAB

/hf2dnK7rNfl3lbqghWcpFdu778hUpIEBixCDL5WiBtpkZdpSw90aERmHJYaW2RGvGRi6zSftLh00KHsPcNUMw==

6Cn/jOLrPapDTEp1Fkq+uz++1Do0eeX7HYqi9rY29CqShzCeI7LEYOoSwYuAJ3xA/DuCdQENPSoJ9KFbO4Wsow==ga1rHIJro8e/yhxjrKYo/nqc5ICQGhrpMNlPkD9n3CjZVPOISkWF7FzUHEzDANeJfkZhcZa21z24aG3rKo5Qnw==MNGsCB8rYlMsRZ2ek2pyQwO7h/sZT8y5ilO9wu08Dwnot/7UMiOEQfDWstY3w5XQQHnvC9WFyCfP4h4QBissyw==EG02S7SADhH1EVT9DD0Z62Y0uY7gIYvxX/uq+IzKSCwB8M2G7Qv9xgZQaQlLpCaeKbux3Y59hHM+KpamGL19Kg==vmaYHEbPAgOJvaEXQl+t8DQKFT1fudEysTy31LTyXjGu6XiltXXHUuZaa2IPyHgBz0Nd7znwsW/S44iql0Fen1kzKioEL3svANui63O3o5xdDeExVM6zOf1wUUh/oldovPweChyoAdMtUzgvCbJk1sYDJf++Nr0FeNW1RB1XG30=
"; string baseQuery = request.RequestUri.Query; if (string.IsNullOrWhiteSpace(baseQuery)) { return request; } else { //读取请求 url query数据 baseQuery = baseQuery.Substring(1); baseQuery = Regex.Match(baseQuery, "(sign=)*(?[\\S]+)").Groups[2].Value; baseQuery = RSADecrypt(privateKey, HttpUtility.UrlDecode(baseQuery.Substring(2))); //将解密后的URL重置解密后的URL请求 request.RequestUri = new Uri($"{request.RequestUri.AbsoluteUri.Split('?')[0]}?{baseQuery}"); return request; } } protected override HttpResponseMessage ProcessResponse(HttpResponseMessage response, CancellationToken cancellationToken) { return response; } } }

2、创建WebApiConfig.cs
iview框架接口参数加密、服务端解密方式_第5张图片
代码:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Http.Cors;

namespace Web.App_Start
{
    public class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.MessageHandlers.Add(new CustomerMessageProcesssingHandler());
            #region 跨域配置
            var allowedMethods = ConfigurationManager.AppSettings["cors:allowedMethodes"];
            var allowedOrigin = ConfigurationManager.AppSettings["cors:allowedOrigin"];
            var allowedHeaders = ConfigurationManager.AppSettings["cors:allowedHeaders"];
            var Cors = new EnableCorsAttribute(allowedOrigin, allowedHeaders, allowedMethods)
            {
                SupportsCredentials = true
            };
            config.EnableCors(Cors);
            #endregion
        }
    }
}

3、Global.asax.cs文件配置
iview框架接口参数加密、服务端解密方式_第6张图片
代码:

  GlobalConfiguration.Configure(WebApiConfig.Register);

你可能感兴趣的:(接口参数加密,C#)