From 6d847ecfe8fa60f0f4b9e4532d4ffebe72a3917a Mon Sep 17 00:00:00 2001 From: liwenxuan <1298531568@qq.com> Date: Thu, 29 Jan 2026 13:43:46 +0800 Subject: [PATCH] =?UTF-8?q?sm4=E5=92=8Cmd5=20=E5=8A=A0=E8=A7=A3=E5=AF=86?= =?UTF-8?q?=20=E9=80=82=E9=85=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 16 ++ .../controller/UploadController.java | 8 +- .../dataupload/utils/sm4/ApiResponse.java | 32 +++ .../utils/sm4/DecryptedArgumentResolver.java | 45 ++++ .../dataupload/utils/sm4/DecryptedBody.java | 9 + .../utils/sm4/EncryptedRequest.java | 20 ++ .../utils/sm4/EncryptedResponseAdvice.java | 113 +++++++++ .../hxjt/dataupload/utils/sm4/ErrorCode.java | 33 +++ .../utils/sm4/GlobalExceptionHandler.java | 22 ++ .../dataupload/utils/sm4/GoApiClient.java | 160 +++++++++++++ .../utils/sm4/RandomStringUtil.java | 47 ++++ .../dataupload/utils/sm4/SM4Interceptor.java | 98 ++++++++ .../hxjt/dataupload/utils/sm4/SM4Utils.java | 217 ++++++++++++++++++ .../hxjt/dataupload/utils/sm4/WebConfig.java | 40 ++++ src/main/resources/application-dev.yml | 11 +- src/main/resources/application-prod.yml | 11 +- src/main/resources/application.yml | 2 +- .../resources/mapper/ZypSingleQueryMapper.xml | 1 - 18 files changed, 878 insertions(+), 7 deletions(-) create mode 100644 src/main/java/com/hxjt/dataupload/utils/sm4/ApiResponse.java create mode 100644 src/main/java/com/hxjt/dataupload/utils/sm4/DecryptedArgumentResolver.java create mode 100644 src/main/java/com/hxjt/dataupload/utils/sm4/DecryptedBody.java create mode 100644 src/main/java/com/hxjt/dataupload/utils/sm4/EncryptedRequest.java create mode 100644 src/main/java/com/hxjt/dataupload/utils/sm4/EncryptedResponseAdvice.java create mode 100644 src/main/java/com/hxjt/dataupload/utils/sm4/ErrorCode.java create mode 100644 src/main/java/com/hxjt/dataupload/utils/sm4/GlobalExceptionHandler.java create mode 100644 src/main/java/com/hxjt/dataupload/utils/sm4/GoApiClient.java create mode 100644 src/main/java/com/hxjt/dataupload/utils/sm4/RandomStringUtil.java create mode 100644 src/main/java/com/hxjt/dataupload/utils/sm4/SM4Interceptor.java create mode 100644 src/main/java/com/hxjt/dataupload/utils/sm4/SM4Utils.java create mode 100644 src/main/java/com/hxjt/dataupload/utils/sm4/WebConfig.java diff --git a/pom.xml b/pom.xml index f1dd710..c54195e 100644 --- a/pom.xml +++ b/pom.xml @@ -212,6 +212,22 @@ 4.1.2 + + org.bouncycastle + bcprov-jdk15to18 + 1.76 + + + commons-codec + commons-codec + 1.15 + + + org.projectlombok + lombok + 1.18.28 + + diff --git a/src/main/java/com/hxjt/dataupload/controller/UploadController.java b/src/main/java/com/hxjt/dataupload/controller/UploadController.java index 45a4935..f4119d4 100644 --- a/src/main/java/com/hxjt/dataupload/controller/UploadController.java +++ b/src/main/java/com/hxjt/dataupload/controller/UploadController.java @@ -14,6 +14,8 @@ import com.hxjt.dataupload.utils.FileUploadUtil; import com.hxjt.dataupload.utils.HttpUtils; import com.hxjt.dataupload.utils.JingWeiDuConverter; import com.hxjt.dataupload.utils.JsonData; +import com.hxjt.dataupload.utils.sm4.ApiResponse; +import com.hxjt.dataupload.utils.sm4.DecryptedBody; import com.hxjt.dataupload.utils.tszy.*; //import com.xxl.job.core.context.XxlJobHelper; import com.xxl.job.core.context.XxlJobHelper; @@ -104,13 +106,13 @@ private ZypSingleQueryMapper zypSingleQueryMapper; /*获取用户有权限的启用状态的表单列表树形结构*/ @RequestMapping(value = "/getOTBILLIDById") - public JsonData getCustomerFormList(@RequestBody Map requestBody) { + public ApiResponse getCustomerFormList(@DecryptedBody Map requestBody) { //System.out.println(requestBody.get("id")); if(!StringUtils.isBlank(requestBody.get("id"))){ Map result = fxfxdxService.getOTBILLIDById(requestBody.get("id")); - return JsonData.buildSuccess(result); + return ApiResponse.success(result); }else{ - return JsonData.buildError("请先输入id"); + return ApiResponse.error(2000,"请先输入id"); } } diff --git a/src/main/java/com/hxjt/dataupload/utils/sm4/ApiResponse.java b/src/main/java/com/hxjt/dataupload/utils/sm4/ApiResponse.java new file mode 100644 index 0000000..338dac3 --- /dev/null +++ b/src/main/java/com/hxjt/dataupload/utils/sm4/ApiResponse.java @@ -0,0 +1,32 @@ +package com.hxjt.dataupload.utils.sm4; + + +import lombok.Data; + +@Data +public class ApiResponse { + private int code; + private String msg; + private T data; + + public ApiResponse() {} + + public ApiResponse(int code, String msg, T data) { + this.code = code; + this.msg = msg; + this.data = data; + } + + public static ApiResponse success(T data) { + if(null==data){ + return new ApiResponse(0, "成功", (T) "成功,没有相关数据"); + }else{ + return new ApiResponse<>(0, "成功", data); + } + + } + + public static ApiResponse error(int code, String msg) { + return new ApiResponse<>(code, msg, null); + } +} \ No newline at end of file diff --git a/src/main/java/com/hxjt/dataupload/utils/sm4/DecryptedArgumentResolver.java b/src/main/java/com/hxjt/dataupload/utils/sm4/DecryptedArgumentResolver.java new file mode 100644 index 0000000..4ce05ea --- /dev/null +++ b/src/main/java/com/hxjt/dataupload/utils/sm4/DecryptedArgumentResolver.java @@ -0,0 +1,45 @@ +package com.hxjt.dataupload.utils.sm4; + +import com.fasterxml.jackson.databind.ObjectMapper; +import lombok.extern.slf4j.Slf4j; +import org.springframework.core.MethodParameter; +import org.springframework.stereotype.Component; +import org.springframework.web.bind.support.WebDataBinderFactory; +import org.springframework.web.context.request.NativeWebRequest; +import org.springframework.web.method.support.HandlerMethodArgumentResolver; +import org.springframework.web.method.support.ModelAndViewContainer; + +import javax.servlet.http.HttpServletRequest; + +@Slf4j +@Component +public class DecryptedArgumentResolver implements HandlerMethodArgumentResolver { + + private final ObjectMapper objectMapper = new ObjectMapper(); + + @Override + public boolean supportsParameter(MethodParameter parameter) { + return parameter.hasParameterAnnotation(DecryptedBody.class); + } + + @Override + public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, + NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { + + HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class); + String decryptedBody = (String) request.getAttribute("decryptedBody"); + + if (decryptedBody != null) { + log.debug("准备解析解密后的数据: {}", decryptedBody); + return objectMapper.readValue(decryptedBody, parameter.getParameterType()); + } + + // 如果没有解密数据,尝试直接解析请求体(非加密模式) + try { + return objectMapper.readValue(request.getInputStream(), parameter.getParameterType()); + } catch (Exception e) { + log.warn("无法解析请求体为 {},返回null", parameter.getParameterType().getSimpleName()); + return null; + } + } +} \ No newline at end of file diff --git a/src/main/java/com/hxjt/dataupload/utils/sm4/DecryptedBody.java b/src/main/java/com/hxjt/dataupload/utils/sm4/DecryptedBody.java new file mode 100644 index 0000000..ac6677e --- /dev/null +++ b/src/main/java/com/hxjt/dataupload/utils/sm4/DecryptedBody.java @@ -0,0 +1,9 @@ +package com.hxjt.dataupload.utils.sm4; + +import java.lang.annotation.*; + +@Target(ElementType.PARAMETER) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface DecryptedBody { +} \ No newline at end of file diff --git a/src/main/java/com/hxjt/dataupload/utils/sm4/EncryptedRequest.java b/src/main/java/com/hxjt/dataupload/utils/sm4/EncryptedRequest.java new file mode 100644 index 0000000..201139e --- /dev/null +++ b/src/main/java/com/hxjt/dataupload/utils/sm4/EncryptedRequest.java @@ -0,0 +1,20 @@ +package com.hxjt.dataupload.utils.sm4; + + + +import lombok.Data; + +@Data +public class EncryptedRequest { + /** + * 加密的数据字段 + * 前端发送的是 "data" 字段,不是 "encryptedFile" + */ + private String data; + + public EncryptedRequest() {} + + public EncryptedRequest(String data) { + this.data = data; + } +} \ No newline at end of file diff --git a/src/main/java/com/hxjt/dataupload/utils/sm4/EncryptedResponseAdvice.java b/src/main/java/com/hxjt/dataupload/utils/sm4/EncryptedResponseAdvice.java new file mode 100644 index 0000000..6ced17a --- /dev/null +++ b/src/main/java/com/hxjt/dataupload/utils/sm4/EncryptedResponseAdvice.java @@ -0,0 +1,113 @@ +package com.hxjt.dataupload.utils.sm4; + + +import com.fasterxml.jackson.databind.ObjectMapper; +import lombok.extern.slf4j.Slf4j; +import org.springframework.core.MethodParameter; +import org.springframework.http.MediaType; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.http.server.ServerHttpRequest; +import org.springframework.http.server.ServerHttpResponse; +import org.springframework.http.server.ServletServerHttpRequest; +import org.springframework.stereotype.Component; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice; + +import javax.servlet.http.HttpServletRequest; + +@Slf4j +@Component +@ControllerAdvice +public class EncryptedResponseAdvice implements ResponseBodyAdvice { + + private final ObjectMapper objectMapper = new ObjectMapper(); + + @Override + public boolean supports(MethodParameter returnType, Class> converterType) { + return true; + } + + @Override + public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, + Class> selectedConverterType, + ServerHttpRequest request, ServerHttpResponse response) { + + HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest(); + + // 检查是否应该加密(可以根据路径或其他条件判断) + boolean shouldEncrypt = shouldEncryptResponse(servletRequest); + if (!shouldEncrypt) { + return body; + } + + // 获取或生成 Auth-key + String authKey = (String) servletRequest.getAttribute("responseAuthKey"); + if (authKey == null) { + authKey = RandomStringUtil.generateRandomString(16); + servletRequest.setAttribute("responseAuthKey", authKey); + } + + // 设置响应头 + response.getHeaders().set("Auth-key", authKey); + + try { + // 只有 ApiResponse 才需要加密 + if (body instanceof ApiResponse) { + ApiResponse apiResponse = (ApiResponse) body; + + // 如果数据不为空,进行加密 + if (apiResponse.getData() != null) { + // 将数据转换为 JSON 字符串 + String jsonData = objectMapper.writeValueAsString(apiResponse.getData()); + + log.debug("准备加密的数据: {}", jsonData); + log.debug("使用的 Auth-key: {}", authKey); + + // 使用 SM4 加密 + String encryptedData = SM4Utils.encrypt(jsonData, authKey); + + log.debug("加密结果长度: {}", encryptedData.length()); + + // 返回格式:{ code: 0, msg: "成功", data: "加密字符串" } + return new ApiResponse<>(apiResponse.getCode(), apiResponse.getMsg(), encryptedData); + } else { + // 数据为空,直接返回原始响应 + return apiResponse; + } + } + + // 如果不是 ApiResponse,直接返回(如文件下载等) + return body; + + } catch (Exception e) { + log.error("响应加密失败", e); + // 加密失败时返回错误响应 + return ApiResponse.error(500, "服务器加密错误: " + e.getMessage()); + } + } + + /** + * 判断是否应该加密响应 + */ + private boolean shouldEncryptResponse(HttpServletRequest request) { + String path = request.getRequestURI(); + + // 可以根据路径排除某些接口 + if (path.contains("/api/debug/") || + path.contains("/actuator/") || + path.contains("/swagger") || + path.contains("/v2/api-docs") || + path.endsWith(".html") || + path.endsWith(".js") || + path.endsWith(".css")) { + return false; + } + + // 检查是否有特殊的请求头表示不需要加密 + if ("false".equalsIgnoreCase(request.getHeader("X-No-Encrypt"))) { + return false; + } + + return true; + } +} \ No newline at end of file diff --git a/src/main/java/com/hxjt/dataupload/utils/sm4/ErrorCode.java b/src/main/java/com/hxjt/dataupload/utils/sm4/ErrorCode.java new file mode 100644 index 0000000..f3f1db2 --- /dev/null +++ b/src/main/java/com/hxjt/dataupload/utils/sm4/ErrorCode.java @@ -0,0 +1,33 @@ +package com.hxjt.dataupload.utils.sm4; + + + +public enum ErrorCode { + SUCCESS(0, "成功"), + DATA_FORMAT_ERROR(100, "提交的数据格式错误!"), + DATA_EMPTY(101, "提交的数据不能为空!"), + KEY_PARAM_EMPTY(102, "关键参数不能为空!"), + DATA_EXISTS(103, "该数据已经存在!请不要重复添加"), + WRITE_FAILED(104, "数据写入失败!"), + QUERY_FAILED(105, "数据查询失败!"), + UPDATE_FAILED(106, "编辑失败!"), + NO_DATA(107, "未能查询到数据!"), + DELETE_FAILED(108, "删除失败"), + AUTH_ERROR(2000, "账户或密码错误!"); + + private final int code; + private final String message; + + ErrorCode(int code, String message) { + this.code = code; + this.message = message; + } + + public int getCode() { + return code; + } + + public String getMessage() { + return message; + } +} \ No newline at end of file diff --git a/src/main/java/com/hxjt/dataupload/utils/sm4/GlobalExceptionHandler.java b/src/main/java/com/hxjt/dataupload/utils/sm4/GlobalExceptionHandler.java new file mode 100644 index 0000000..377bf1c --- /dev/null +++ b/src/main/java/com/hxjt/dataupload/utils/sm4/GlobalExceptionHandler.java @@ -0,0 +1,22 @@ +package com.hxjt.dataupload.utils.sm4; + + +import lombok.extern.slf4j.Slf4j; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +@Slf4j +@RestControllerAdvice +public class GlobalExceptionHandler { + + @ExceptionHandler(Exception.class) + public ApiResponse handleException(Exception e) { + log.error("系统异常:", e); + return ApiResponse.error(500, "服务器错误"); + } + + @ExceptionHandler(IllegalArgumentException.class) + public ApiResponse handleIllegalArgumentException(IllegalArgumentException e) { + return ApiResponse.error(400, e.getMessage()); + } +} \ No newline at end of file diff --git a/src/main/java/com/hxjt/dataupload/utils/sm4/GoApiClient.java b/src/main/java/com/hxjt/dataupload/utils/sm4/GoApiClient.java new file mode 100644 index 0000000..5ce0efd --- /dev/null +++ b/src/main/java/com/hxjt/dataupload/utils/sm4/GoApiClient.java @@ -0,0 +1,160 @@ +package com.hxjt.dataupload.utils.sm4; + + +import com.alibaba.fastjson2.JSON; +import com.alibaba.fastjson2.JSONObject; +import lombok.extern.slf4j.Slf4j; +import org.apache.http.HttpResponse; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.util.EntityUtils; +import org.springframework.stereotype.Component; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.Map; + +@Slf4j +@Component +public class GoApiClient { + + private static final int TIMEOUT = 5000; + + /** + * 调用 Go 接口(使用加密通信) + * @param url Go接口地址 + * @param param 请求参数 + * @param userKey User-Key + * @param userToken User-Token + * @return 解密后的响应字符串 + * @throws IOException + */ + public String callGoApi(String url, Object param, String userKey, String userToken) throws IOException { + // 1. 生成随机 Auth-key(16位) + String authKey = RandomStringUtil.generateRandomString(16); + + // 2. 加密请求数据 + String encryptedData; + try { + String jsonParam = JSON.toJSONString(param); + encryptedData = SM4Utils.encrypt(jsonParam, authKey); + } catch (Exception e) { + log.error("加密请求数据失败", e); + throw new IOException("加密请求数据失败: " + e.getMessage(), e); + } + + // 3. 构建加密请求体 + Map encryptedBody = new HashMap<>(); + encryptedBody.put("data", encryptedData); // Go后端期望data字段 + String requestBody = JSON.toJSONString(encryptedBody); + + // 4. 发送 HTTP 请求 + CloseableHttpClient httpClient = null; + try { + RequestConfig requestConfig = RequestConfig.custom() + .setConnectTimeout(TIMEOUT) + .setSocketTimeout(TIMEOUT) + .setConnectionRequestTimeout(TIMEOUT) + .build(); + + httpClient = HttpClients.custom() + .setDefaultRequestConfig(requestConfig) + .build(); + + HttpPost httpPost = new HttpPost(url); + + // 设置请求头 + httpPost.setHeader("User-Key", userKey); + httpPost.setHeader("User-Token", userToken); + httpPost.setHeader("Auth-key", authKey); + httpPost.setHeader("Content-Type", "application/json; charset=UTF-8"); + + // 设置请求体 + StringEntity entity = new StringEntity(requestBody, StandardCharsets.UTF_8); + httpPost.setEntity(entity); + + // 执行请求 + HttpResponse response = httpClient.execute(httpPost); + int statusCode = response.getStatusLine().getStatusCode(); + + if (statusCode != 200) { + String errorResponse = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8); + throw new IOException("HTTP 请求失败,状态码: " + statusCode + ", 响应: " + errorResponse); + } + + // 获取响应体 + String responseBody = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8); + + // 获取响应头中的 Auth-key + org.apache.http.Header[] authKeyHeaders = response.getHeaders("Auth-key"); + String responseAuthKey = null; + if (authKeyHeaders != null && authKeyHeaders.length > 0) { + responseAuthKey = authKeyHeaders[0].getValue(); + } + + // 5. 解密响应数据 + if (responseAuthKey != null && !responseAuthKey.isEmpty()) { + return decryptGoResponse(responseBody, responseAuthKey); + } else { + log.warn("响应头中没有找到 Auth-key,返回原始响应"); + return responseBody; + } + + } catch (Exception e) { + log.error("HTTP 请求异常", e); + throw new IOException("HTTP 请求异常: " + e.getMessage(), e); + } finally { + if (httpClient != null) { + try { + httpClient.close(); + } catch (IOException e) { + log.error("关闭 HTTP 客户端失败", e); + } + } + } + } + + /** + * 解密 Go 后端的响应 + */ + private String decryptGoResponse(String responseBody, String authKey) throws Exception { + try { + // 解析 Go 的响应 + JSONObject responseJson = JSON.parseObject(responseBody); + int code = responseJson.getIntValue("code"); + String msg = responseJson.getString("msg"); + String encryptedData = responseJson.getString("data"); + + if (encryptedData != null && !encryptedData.isEmpty()) { + // 解密数据 + String decryptedData = SM4Utils.decrypt(encryptedData, authKey); + + // 重新构建响应 + JSONObject result = new JSONObject(); + result.put("code", code); + result.put("msg", msg); + + try { + // 尝试将解密后的字符串解析为 JSON 对象 + Object dataObj = JSON.parse(decryptedData); + result.put("data", dataObj); + } catch (Exception e) { + // 如果解析失败,直接使用字符串 + result.put("data", decryptedData); + } + + return result.toJSONString(); + } else { + return responseBody; + } + + } catch (Exception e) { + log.error("解密 Go 响应数据失败", e); + throw new Exception("解密 Go 响应数据失败: " + e.getMessage(), e); + } + } +} \ No newline at end of file diff --git a/src/main/java/com/hxjt/dataupload/utils/sm4/RandomStringUtil.java b/src/main/java/com/hxjt/dataupload/utils/sm4/RandomStringUtil.java new file mode 100644 index 0000000..38846ba --- /dev/null +++ b/src/main/java/com/hxjt/dataupload/utils/sm4/RandomStringUtil.java @@ -0,0 +1,47 @@ +package com.hxjt.dataupload.utils.sm4; + +import org.apache.commons.codec.binary.Hex; +import org.springframework.stereotype.Component; + +import java.security.SecureRandom; + +@Component +public class RandomStringUtil { + + private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + private static final SecureRandom SECURE_RANDOM = new SecureRandom(); + + /** + * 生成指定长度的随机字符串 + */ + public static String generateRandomString(int length) { + StringBuilder sb = new StringBuilder(length); + for (int i = 0; i < length; i++) { + int index = SECURE_RANDOM.nextInt(CHARACTERS.length()); + sb.append(CHARACTERS.charAt(index)); + } + return sb.toString(); + } + + /** + * 获取UUID + */ + public static String generateUUID() { + byte[] randomBytes = new byte[16]; + SECURE_RANDOM.nextBytes(randomBytes); + randomBytes[6] &= 0x0f; /* clear version */ + randomBytes[6] |= 0x40; /* set to version 4 */ + randomBytes[8] &= 0x3f; /* clear variant */ + randomBytes[8] |= 0x80; /* set to IETF variant */ + + char[] uuidChars = Hex.encodeHex(randomBytes, false); + StringBuilder uuid = new StringBuilder(36); + for (int i = 0; i < uuidChars.length; i++) { + if (i == 8 || i == 12 || i == 16 || i == 20) { + uuid.append('-'); + } + uuid.append(uuidChars[i]); + } + return uuid.toString(); + } +} diff --git a/src/main/java/com/hxjt/dataupload/utils/sm4/SM4Interceptor.java b/src/main/java/com/hxjt/dataupload/utils/sm4/SM4Interceptor.java new file mode 100644 index 0000000..6342ea8 --- /dev/null +++ b/src/main/java/com/hxjt/dataupload/utils/sm4/SM4Interceptor.java @@ -0,0 +1,98 @@ +package com.hxjt.dataupload.utils.sm4; + + + +import com.fasterxml.jackson.databind.ObjectMapper; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; +import org.springframework.web.servlet.HandlerInterceptor; +import org.springframework.web.servlet.ModelAndView; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.BufferedReader; +import java.io.PrintWriter; + +@Slf4j +@Component +public class SM4Interceptor implements HandlerInterceptor { + + private final ObjectMapper objectMapper = new ObjectMapper(); + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + String authKey = request.getHeader("Auth-key"); + String contentType = request.getHeader("Content-Type"); + + log.debug("请求拦截 - Auth-key: {}, Content-Type: {}", authKey, contentType); + + // 如果是JSON请求且需要解密 + if (contentType != null && contentType.contains("application/json") && authKey != null) { + try { + // 读取请求体 + StringBuilder requestBody = new StringBuilder(); + try (BufferedReader reader = request.getReader()) { + String line; + while ((line = reader.readLine()) != null) { + requestBody.append(line); + } + } + + if (requestBody.length() > 0) { + String requestBodyStr = requestBody.toString(); + //log.debug("原始请求体: {}", requestBodyStr); + + // 解析加密请求 + EncryptedRequest encryptedRequest = objectMapper.readValue(requestBodyStr, EncryptedRequest.class); + + if (encryptedRequest.getData() != null && !encryptedRequest.getData().isEmpty()) { + //log.debug("获取到加密数据: {}", encryptedRequest.getData().substring(0, Math.min(50, encryptedRequest.getData().length())) + "..."); + + // 解密数据 + String decryptedData = SM4Utils.decrypt(encryptedRequest.getData(), authKey); + //log.debug("解密后的数据: {}", decryptedData); + + // 将解密后的数据重新放入请求体 + request.setAttribute("decryptedBody", decryptedData); + + // 记录解密成功 + //log.info("请求解密成功,Auth-key: {}", authKey); + } else { + log.warn("加密数据为空,跳过解密"); + } + } + } catch (Exception e) { + log.error("请求解密失败", e); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.setContentType("application/json;charset=UTF-8"); + + ApiResponse errorResponse = ApiResponse.error(100, "提交的数据格式错误!"); + PrintWriter writer = response.getWriter(); + writer.write(objectMapper.writeValueAsString(errorResponse)); + writer.flush(); + return false; + } + } + + return true; + } + + @Override + public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, + ModelAndView modelAndView) throws Exception { + // 生成新的随机密钥 + String newAuthKey = RandomStringUtil.generateRandomString(16); + response.setHeader("Auth-key", newAuthKey); + request.setAttribute("responseAuthKey", newAuthKey); + + //log.debug("生成新的 Auth-key: {}", newAuthKey); + } + + @Override + public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, + Exception ex) throws Exception { + // 清理 + request.removeAttribute("decryptedBody"); + request.removeAttribute("responseAuthKey"); + } +} \ No newline at end of file diff --git a/src/main/java/com/hxjt/dataupload/utils/sm4/SM4Utils.java b/src/main/java/com/hxjt/dataupload/utils/sm4/SM4Utils.java new file mode 100644 index 0000000..28c2a26 --- /dev/null +++ b/src/main/java/com/hxjt/dataupload/utils/sm4/SM4Utils.java @@ -0,0 +1,217 @@ +package com.hxjt.dataupload.utils.sm4; + + + +import org.bouncycastle.crypto.engines.SM4Engine; +import org.bouncycastle.crypto.modes.CBCBlockCipher; +import org.bouncycastle.crypto.paddings.PKCS7Padding; +import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher; +import org.bouncycastle.crypto.params.KeyParameter; +import org.bouncycastle.crypto.params.ParametersWithIV; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +import java.nio.charset.StandardCharsets; + +@Component +public class SM4Utils { + + // Go 后端的 Sm4Key - 用作加密密钥 + @Value("${sm4.key:hengxingaokeApp1}") + private String sm4Key; + + // Go 后端的 Sm4Token - 默认用作 IV + @Value("${sm4.token:04TzMuvkHm_EZnHm}") + private String sm4Token; + + // 前端使用的 systemKey(仅用于与前端对比验证) + @Value("${sm4.system-key:appKeyQinDongV01}") + private String systemKey; + + private static String SM4_KEY_PROCESSED; + private static String SM4_TOKEN_PROCESSED; + private static String SYSTEM_KEY_HEX; + + @PostConstruct + public void init() { + // Go 的方式:处理为16字节(不是转16进制!) + SM4_KEY_PROCESSED = processString(sm4Key, 16, "s"); + SM4_TOKEN_PROCESSED = processString(sm4Token, 16, "s"); + + // 前端的 systemKey 转16进制(仅用于验证) + SYSTEM_KEY_HEX = stringToHex(systemKey); + + /*System.out.println("=== SM4Utils 初始化 ==="); + System.out.println("Go 的 Sm4Key: " + sm4Key); + System.out.println("Go 的 Sm4Key(处理后16字节): " + SM4_KEY_PROCESSED); + System.out.println("Go 的 Sm4Token: " + sm4Token); + System.out.println("Go 的 Sm4Token(处理后16字节): " + SM4_TOKEN_PROCESSED); + System.out.println("前端的 VITE_APP_SYSTEM_KEY: " + systemKey); + System.out.println("前端的 systemKey(hex): " + SYSTEM_KEY_HEX); + System.out.println("注意:Java 应该使用 Go 的 Sm4Key,而不是前端的 systemKey!");*/ + } + + /** + * 处理字符串为指定长度(与 Go 的 ProcessString 完全一致) + * 超过截断,不足用 pad 补全 + */ + private static String processString(String s, int length, String pad) { + // 如果字符串长度已经符合要求,直接返回 + if (s.length() == length) { + return s; + } + // 如果字符串长度超过了要求,截取指定长度的部分 + if (s.length() > length) { + return s.substring(0, length); + } + // 如果字符串长度不足,使用pad字符串进行补充 + StringBuilder sb = new StringBuilder(s); + while (sb.length() < length) { + sb.append(pad); + } + return sb.substring(0, length); // 确保不会超过长度 + } + + /** + * 字符串转16进制(仅用于与前端对比) + */ + private static String stringToHex(String str) { + byte[] bytes = str.getBytes(StandardCharsets.UTF_8); + StringBuilder hex = new StringBuilder(); + for (byte b : bytes) { + hex.append(String.format("%02x", b)); + } + return hex.toString(); + } + + /** + * 判断是否为32位16进制字符串 + */ + private static boolean isValidHex32(String str) { + if (str == null || str.length() != 32) return false; + return str.matches("[0-9a-fA-F]{32}"); + } + + /** + * 加密方法(与 Go 的 SM4Encrypt 完全一致) + * @param data 要加密的字符串数据 + * @param customKey 自定义密钥(Auth-key),如果提供则用作 IV + * @return 加密后的16进制字符串 + */ + public static String encrypt(String data, String customKey) throws Exception { + // 1. 确定加密密钥(使用 Go 的 Sm4Key) + String keyStr = SM4_KEY_PROCESSED; + byte[] keyBytes = keyStr.getBytes(StandardCharsets.UTF_8); + + // 2. 确定 IV(如果有 customKey 则用 customKey,否则用 Sm4Token) + String ivStr = SM4_TOKEN_PROCESSED; + if (customKey != null && !customKey.isEmpty()) { + // Go 的逻辑:如果有 customKey,处理为16字节 + ivStr = processString(customKey, 16, "s"); + } + byte[] ivBytes = ivStr.getBytes(StandardCharsets.UTF_8); + + /*System.out.println("=== Java 加密参数 ==="); + System.out.println("加密密钥: " + keyStr + " (UTF-8字节: " + bytesToHex(keyBytes) + ")"); + System.out.println("IV: " + ivStr + " (UTF-8字节: " + bytesToHex(ivBytes) + ")"); + System.out.println("原始数据: " + data);*/ + + // 3. 使用 BouncyCastle 进行 SM4-CBC 加密 + PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher( + new CBCBlockCipher(new SM4Engine()), new PKCS7Padding() + ); + + cipher.init(true, new ParametersWithIV(new KeyParameter(keyBytes), ivBytes)); + + byte[] inputBytes = data.getBytes(StandardCharsets.UTF_8); + byte[] outputBytes = new byte[cipher.getOutputSize(inputBytes.length)]; + + int length1 = cipher.processBytes(inputBytes, 0, inputBytes.length, outputBytes, 0); + int length2 = cipher.doFinal(outputBytes, length1); + + byte[] encryptedBytes = new byte[length1 + length2]; + System.arraycopy(outputBytes, 0, encryptedBytes, 0, encryptedBytes.length); + + String result = bytesToHex(encryptedBytes); + //System.out.println("加密结果(hex): " + result); + + return result; + } + + /** + * 解密方法(与 Go 的 SM4Decrypt 完全一致) + * @param encryptedHex 加密后的16进制字符串 + * @param customKey 自定义密钥(Auth-key),如果提供则用作 IV + * @return 解密后的字符串 + */ + public static String decrypt(String encryptedHex, String customKey) throws Exception { + // 1. 确定加密密钥(使用 Go 的 Sm4Key) + String keyStr = SM4_KEY_PROCESSED; + byte[] keyBytes = keyStr.getBytes(StandardCharsets.UTF_8); + + // 2. 确定 IV(如果有 customKey 则用 customKey,否则用 Sm4Token) + String ivStr = SM4_TOKEN_PROCESSED; + if (customKey != null && !customKey.isEmpty()) { + // Go 的逻辑:如果有 customKey,处理为16字节 + ivStr = processString(customKey, 16, "s"); + } + byte[] ivBytes = ivStr.getBytes(StandardCharsets.UTF_8); + + /*System.out.println("=== Java 解密参数 ==="); + System.out.println("解密密钥: " + keyStr + " (UTF-8字节: " + bytesToHex(keyBytes) + ")"); + System.out.println("IV: " + ivStr + " (UTF-8字节: " + bytesToHex(ivBytes) + ")"); + System.out.println("加密数据(hex): " + encryptedHex);*/ + + // 3. 转换加密数据 + byte[] encryptedBytes = hexToBytes(encryptedHex); + + // 4. 使用 BouncyCastle 进行 SM4-CBC 解密 + PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher( + new CBCBlockCipher(new SM4Engine()), new PKCS7Padding() + ); + + cipher.init(false, new ParametersWithIV(new KeyParameter(keyBytes), ivBytes)); + + byte[] outputBytes = new byte[cipher.getOutputSize(encryptedBytes.length)]; + + int length1 = cipher.processBytes(encryptedBytes, 0, encryptedBytes.length, outputBytes, 0); + int length2 = cipher.doFinal(outputBytes, length1); + + byte[] decryptedBytes = new byte[length1 + length2]; + System.arraycopy(outputBytes, 0, decryptedBytes, 0, decryptedBytes.length); + + String result = new String(decryptedBytes, StandardCharsets.UTF_8); + //System.out.println("解密结果: " + result); + + return result; + } + + /** + * 字节数组转16进制字符串 + */ + private static String bytesToHex(byte[] bytes) { + StringBuilder hex = new StringBuilder(); + for (byte b : bytes) { + hex.append(String.format("%02x", b)); + } + return hex.toString(); + } + + /** + * 16进制字符串转字节数组 + */ + private static byte[] hexToBytes(String hex) { + if (hex.length() % 2 != 0) { + throw new IllegalArgumentException("Hex string length must be even"); + } + byte[] bytes = new byte[hex.length() / 2]; + for (int i = 0; i < bytes.length; i++) { + int index = i * 2; + bytes[i] = (byte) Integer.parseInt(hex.substring(index, index + 2), 16); + } + return bytes; + } + + +} \ No newline at end of file diff --git a/src/main/java/com/hxjt/dataupload/utils/sm4/WebConfig.java b/src/main/java/com/hxjt/dataupload/utils/sm4/WebConfig.java new file mode 100644 index 0000000..b38fdb5 --- /dev/null +++ b/src/main/java/com/hxjt/dataupload/utils/sm4/WebConfig.java @@ -0,0 +1,40 @@ +package com.hxjt.dataupload.utils.sm4; + + + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.method.support.HandlerMethodArgumentResolver; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +import java.util.List; + +@Configuration +public class WebConfig implements WebMvcConfigurer { + + @Autowired + private SM4Interceptor sm4Interceptor; + + @Autowired + private DecryptedArgumentResolver decryptedArgumentResolver; + + @Override + public void addInterceptors(InterceptorRegistry registry) { + registry.addInterceptor(sm4Interceptor) + .addPathPatterns("/**") + .excludePathPatterns( + "/error", + "/api/sm4-test/**", // 排除测试接口 + "/actuator/**", // 排除监控接口 + "/swagger-ui/**", // 排除 Swagger + "/v2/api-docs", // 排除 API 文档 + "/webjars/**" // 排除静态资源 + ); + } + + @Override + public void addArgumentResolvers(List resolvers) { + resolvers.add(decryptedArgumentResolver); + } +} \ No newline at end of file diff --git a/src/main/resources/application-dev.yml b/src/main/resources/application-dev.yml index 8ca325c..693cadc 100644 --- a/src/main/resources/application-dev.yml +++ b/src/main/resources/application-dev.yml @@ -36,7 +36,7 @@ spring: driver-class-name: com.mysql.cj.jdbc.Driver password: kPMP6NafMsdccxDX #url: jdbc:mysql://127.0.0.1:3306/hengxingaoke_tes?allowPublicKeyRetrieval=true&uuseUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&tinyInt1isBit=false - url: jdbc:mysql://36.133.126.182:3306/hr_new?allowPublicKeyRetrieval=true&uuseUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&tinyInt1isBit=false + url: jdbc:mysql://36.133.123.69:13366/hr_new?allowPublicKeyRetrieval=true&uuseUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&tinyInt1isBit=false username: hr_new hrnewlowcodetest: driver-class-name: com.mysql.cj.jdbc.Driver @@ -113,3 +113,12 @@ xxl: enabled: true realtimeDataTopic: /iot/10@ningyanghuagongchany20250422172632/thirdParty/realtimeData +# Go 后端的 SM4 配置(Java 应该使用这些) +sm4: + key: "hengxingaokeApp1" # Go 的 Sm4Key + token: "04TzMuvkHm_EZnHm" # Go 的 Sm4Token + + + system-key: "appKeyQinDongV01" + app-key: "04TzMuvkHm_EZnHm" + diff --git a/src/main/resources/application-prod.yml b/src/main/resources/application-prod.yml index 9e938d8..6f85ac4 100644 --- a/src/main/resources/application-prod.yml +++ b/src/main/resources/application-prod.yml @@ -36,7 +36,7 @@ spring: driver-class-name: com.mysql.cj.jdbc.Driver password: kPMP6NafMsdccxDX #url: jdbc:mysql://127.0.0.1:3306/hengxingaoke_tes?allowPublicKeyRetrieval=true&uuseUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&tinyInt1isBit=false - url: jdbc:mysql://36.133.126.182:3306/hr_new?allowPublicKeyRetrieval=true&uuseUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&tinyInt1isBit=false + url: jdbc:mysql://36.133.123.69:13366/hr_new?allowPublicKeyRetrieval=true&uuseUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&tinyInt1isBit=false username: hr_new hrnewlowcodetest: driver-class-name: com.mysql.cj.jdbc.Driver @@ -115,3 +115,12 @@ xxl: enabled: true realtimeDataTopic: /iot/10@ningyanghuagongchany20250422172632/thirdParty/realtimeData +# Go 后端的 SM4 配置(Java 应该使用这些) +sm4: + key: "hengxingaokeApp1" # Go 的 Sm4Key + token: "04TzMuvkHm_EZnHm" # Go 的 Sm4Token + + + system-key: "appKeyQinDongV01" + app-key: "04TzMuvkHm_EZnHm" + diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index ea88ff2..eb49595 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -1,5 +1,5 @@ spring: profiles: - active: prod + active: dev server: port: 8118 \ No newline at end of file diff --git a/src/main/resources/mapper/ZypSingleQueryMapper.xml b/src/main/resources/mapper/ZypSingleQueryMapper.xml index ccf079f..70ed4e6 100644 --- a/src/main/resources/mapper/ZypSingleQueryMapper.xml +++ b/src/main/resources/mapper/ZypSingleQueryMapper.xml @@ -51,7 +51,6 @@ COALESCE(',' + NULLIF(A.prosafe, ''), ''), 1, 1, '' ), 69) AS shigongrenyuanxingmi, A.SDUNITNAME AS zuoyedanwei, - A.SDUNITNAME AS zuoyedanwei, -- 通过机构路径改进 (case when A.UNITID is null then '是'