using System.Text; using System.Web; using Common; using Infrastructure; namespace Filters { public class DecryptMiddleware { public static int Do(HttpContext context) { var request = context.Request; string cipherText = ""; try { if(request.Method.ToLower() == "get") { cipherText = request.Query["value"]; cipherText = HttpUtility.UrlDecode(cipherText); cipherText = Decrypt(cipherText); cipherText = HttpUtility.UrlDecode(cipherText); } else if(request.Method.ToLower() == "delete") { string path = request.Path.Value; string value = path.Substring(path.LastIndexOf("/") + 1); path = path.Substring(0, path.LastIndexOf("/") + 1); value = Decrypt(value); path += value; request.Path = new PathString(path); request.RouteValues["id"] = value; } else { using var reader = new StreamReader(request.Body, leaveOpen: true); cipherText = reader.ReadToEnd(); if(cipherText.StartsWith("value=")) { cipherText = cipherText.Replace("value=", ""); } cipherText = Decrypt(cipherText); } if (string.IsNullOrWhiteSpace(cipherText)) { return 1; } if(request.Method.ToLower() == "get") { cipherText = GetParams(cipherText); var queryDict = Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery(cipherText); var newQuery = new QueryCollection(queryDict); request.Query = newQuery; request.QueryString = new QueryString("?" + cipherText); } else if(request.Method.ToLower() == "delete") {} else { var bytes = Encoding.UTF8.GetBytes(cipherText); var ms = new MemoryStream(bytes); request.Body = ms; // 替换为明文 request.ContentLength = bytes.Length; ms.Position = 0; } } catch (Exception ex) { context.Response.StatusCode = StatusCodes.Status400BadRequest; Utils.WriteLog(ex.ToString(), "解密异常"); return 2; } return 0; } public static string Decrypt(string str) { if(string.IsNullOrEmpty(str)) return ""; str = str.Trim('"'); str = Encoding.UTF8.GetString(Convert.FromBase64String(str)); var options = App.OptionsSetting; var aes = options.Aes; return Dbconn.AesDecrypt(str, aes.EncodeKey, aes.EncodeIv, aes.EncodeMode, aes.EncodePadding); } #region 接口通用DES解密 public static string DesDecrypt(string content) { content = HttpUtility.UrlDecode(content); return Dbconn.DesDecrypt(content, "&L^kg4N9"); } #endregion public static string GetParam(string content, string key) { if(content.StartsWith("?")) content = content.Substring(1); string[] data = content.Split('&'); foreach(string sub in data) { if(sub.StartsWith(key + "=")) { return sub.Substring(sub.IndexOf("=") + 1); } } return ""; } public static string GetParams(string content) { SortedList req = Newtonsoft.Json.JsonConvert.DeserializeObject>(content); return Function.BuildQueryString(req); } } }