EncryptRestInterceptor.java 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. package jnpf.encrypt;
  2. import cn.hutool.core.net.url.UrlQuery;
  3. import com.alibaba.fastjson.JSON;
  4. import com.alibaba.fastjson.JSONObject;
  5. import jakarta.servlet.http.HttpServletRequest;
  6. import jakarta.servlet.http.HttpServletResponse;
  7. import jnpf.annotation.EncryptApi;
  8. import jnpf.constant.GlobalConst;
  9. import jnpf.constant.MsgCode;
  10. import jnpf.exception.EncryptFailException;
  11. import jnpf.util.DesUtil;
  12. import jnpf.util.StringUtil;
  13. import jnpf.wrapper.MyRequestWrapper;
  14. import lombok.extern.slf4j.Slf4j;
  15. import org.springframework.http.MediaType;
  16. import org.springframework.util.StringUtils;
  17. import org.springframework.web.method.HandlerMethod;
  18. import org.springframework.web.servlet.AsyncHandlerInterceptor;
  19. import java.net.URLDecoder;
  20. import java.nio.charset.StandardCharsets;
  21. import java.util.*;
  22. /**
  23. * 接口传输加密
  24. * 支持请求类型:
  25. * application/json
  26. * application/x-www-form-urlencoded
  27. */
  28. @Slf4j
  29. public class EncryptRestInterceptor implements AsyncHandlerInterceptor {
  30. private static final String ENCRYPT_KEY = "encryptData";
  31. @Override
  32. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
  33. try {
  34. if (handler instanceof HandlerMethod && request instanceof MyRequestWrapper) {
  35. HandlerMethod method = (HandlerMethod) handler;
  36. EncryptApi methodAnnotation = method.getMethodAnnotation(EncryptApi.class);
  37. if (methodAnnotation != null && methodAnnotation.encryptRequest()) {
  38. MyRequestWrapper myRequest = (MyRequestWrapper) request;
  39. // 需要对数据进行加密解密
  40. // application/json
  41. // application/x-www-form-urlencoded
  42. String contentType = request.getContentType();
  43. if (contentType != null) {
  44. myRequest.wrapperRequestData();
  45. String requestBody = null;
  46. boolean canEncrypt = false;
  47. if ((StringUtils.substringMatch(contentType, 0,
  48. MediaType.APPLICATION_FORM_URLENCODED_VALUE)) || "get".equalsIgnoreCase(request.getMethod())) {
  49. // 1.application/x-www-form-urlencoded 支持参数在body或者在param
  50. canEncrypt = true;
  51. requestBody = convertFormToString(request);
  52. if ("{}".equals(requestBody)) {
  53. requestBody = URLDecoder.decode(myRequest.getRequestBody());
  54. Map<CharSequence, CharSequence> uriToListToMap = new UrlQuery().parse(requestBody, GlobalConst.DEFAULT_CHARSET).getQueryMap();
  55. requestBody = JSONObject.toJSONString(uriToListToMap);
  56. }
  57. } else if (StringUtils.substringMatch(contentType, 0, MediaType.APPLICATION_JSON_VALUE)) {
  58. // application/json 支持加密参数在body
  59. canEncrypt = true;
  60. requestBody = myRequest.getRequestBody();
  61. }
  62. if (canEncrypt) {
  63. if (requestBody != null && !"{}".equals(requestBody)) {
  64. JSONObject jsonBody = JSON.parseObject(requestBody);
  65. JSON result = decodeApi(jsonBody);
  66. if (result != null) {
  67. myRequest.setRequestBody(result.toJSONString());
  68. if (result instanceof JSONObject) {
  69. myRequest.addAllParameters((Map<String, Object>) result);
  70. }
  71. return true;
  72. }
  73. }
  74. }
  75. }
  76. throw encryptFailException();
  77. }
  78. }
  79. } catch (EncryptFailException eex) {
  80. throw eex;
  81. } catch (Exception e) {
  82. log.error("解密失败, 异常地址:{}", request.getServletPath(), e);
  83. throw encryptFailException();
  84. }
  85. return true;
  86. }
  87. /**
  88. * Pamams参数转JSON字符串
  89. *
  90. * @param request
  91. * @return
  92. */
  93. private String convertFormToString(HttpServletRequest request) {
  94. Map<String, String> result = new HashMap<>(8);
  95. Enumeration<String> parameterNames = request.getParameterNames();
  96. while (parameterNames.hasMoreElements()) {
  97. String name = parameterNames.nextElement();
  98. result.put(name, request.getParameter(name));
  99. }
  100. try {
  101. return JSON.toJSONString(result);
  102. } catch (Exception e) {
  103. throw new IllegalArgumentException(e);
  104. }
  105. }
  106. /**
  107. * 请求内容解密
  108. *
  109. * @param body
  110. * @return
  111. */
  112. public JSON decodeApi(JSON body) {
  113. try {
  114. JSONObject jsonObject = (JSONObject) body;
  115. String content = jsonObject.getOrDefault(ENCRYPT_KEY, "").toString();
  116. if (!StringUtil.isEmpty(content)) {
  117. content = decryptData(content);
  118. return (JSON) JSON.parse(content);
  119. }
  120. } catch (Exception e) {
  121. log.error("解密失败, 文本: {}", body, e);
  122. }
  123. return null;
  124. }
  125. /**
  126. * 文本解密
  127. *
  128. * @param data
  129. * @return
  130. */
  131. protected String decryptData(String data) {
  132. if (StringUtil.isEmpty(data)) {
  133. return data;
  134. }
  135. if (Objects.equals(data.charAt(0), '"') && Objects.equals(data.charAt(data.length() - 1), '"')) {
  136. data = data.substring(1, data.length() - 1);
  137. }
  138. return DesUtil.aesOrDecode(data, false, true);
  139. }
  140. private EncryptFailException encryptFailException() {
  141. throw new EncryptFailException(MsgCode.FA051.get());
  142. }
  143. }