265  
查询码:00000481
iview框架接口参数加密、服务端解密方式
作者: 魏漫漫 于 2020年01月16日 发布在分类 / 人防组 / 人防后端 下,并于 2020年01月16日 编辑

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

引入加密:

import JSEncrypt from "jsencrypt";

 import Qs from 'qs'

package.json:中jsencrypt的版本号:




代码:

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)
    }
第二、服务端解密:
项目结构:

1、创建解密类文件CustomerMessageProcesssingHandler.cs


代码:


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;
            }
        }
        /// <summary>
        /// 解密Url请求
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        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 = "<RSAKeyValue><Modulus>5m9m14XH3oqLJ8bNGw9e4rGpXpcktv9MSkHSVFVMjHbfv+SJ5v0ubqQxa5YjLN4vc49z7SVju8s0X4gZ6AzZTn06jzWOgyPRV54Q4I0DCYadWW4Ze3e+BOtwgVU1Og3qHKn8vygoj40J6U85Z/PTJu3hN1m75Zr195ju7g9v4Hk=</Modulus><Exponent>AQAB</Exponent><P>/hf2dnK7rNfl3lbqghWcpFdu778hUpIEBixCDL5WiBtpkZdpSw90aERmHJYaW2RGvGRi6zSftLh00KHsPcNUMw==</P><Q>6Cn/jOLrPapDTEp1Fkq+uz++1Do0eeX7HYqi9rY29CqShzCeI7LEYOoSwYuAJ3xA/DuCdQENPSoJ9KFbO4Wsow==</Q><DP>ga1rHIJro8e/yhxjrKYo/nqc5ICQGhrpMNlPkD9n3CjZVPOISkWF7FzUHEzDANeJfkZhcZa21z24aG3rKo5Qnw==</DP><DQ>MNGsCB8rYlMsRZ2ek2pyQwO7h/sZT8y5ilO9wu08Dwnot/7UMiOEQfDWstY3w5XQQHnvC9WFyCfP4h4QBissyw==</DQ><InverseQ>EG02S7SADhH1EVT9DD0Z62Y0uY7gIYvxX/uq+IzKSCwB8M2G7Qv9xgZQaQlLpCaeKbux3Y59hHM+KpamGL19Kg==</InverseQ><D>vmaYHEbPAgOJvaEXQl+t8DQKFT1fudEysTy31LTyXjGu6XiltXXHUuZaa2IPyHgBz0Nd7znwsW/S44iql0Fen1kzKioEL3svANui63O3o5xdDeExVM6zOf1wUUh/oldovPweChyoAdMtUzgvCbJk1sYDJf++Nr0FeNW1RB1XG30=</D></RSAKeyValue>";

            string baseQuery = request.RequestUri.Query;
            if (string.IsNullOrWhiteSpace(baseQuery))
            {
                return request;
            }
            else
            {
                //读取请求 url query数据
                baseQuery = baseQuery.Substring(1);
                baseQuery = Regex.Match(baseQuery, "(sign=)*(?<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




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文件配置

代码:

GlobalConfiguration.Configure(WebApiConfig.Register);



 推荐知识

 历史版本

修改日期 修改人 备注
2020-01-16 17:39:56[当前版本] 魏漫漫 创建版本

 附件

附件类型

PNGPNG

知识分享平台 -V 4.8.7 -wcp