| | |
| | | import javax.servlet.http.HttpServletResponse; |
| | | import java.io.BufferedReader; |
| | | import java.io.IOException; |
| | | import java.nio.charset.StandardCharsets; |
| | | import java.rmi.ServerException; |
| | | |
| | | public class SmCryptoFilter implements Filter { |
| | |
| | | HttpServletResponse httpResponse = (HttpServletResponse) response; |
| | | |
| | | try { |
| | | // 设置请求和响应的编码为 UTF-8 |
| | | request.setCharacterEncoding("UTF-8"); |
| | | response.setCharacterEncoding("UTF-8"); |
| | | response.setContentType("application/json;charset=UTF-8"); |
| | | |
| | | // 对请求进行解密 |
| | | String decryptedRequestBody = decryptRequest(httpRequest); |
| | | logger.info("解密后数据={}", decryptedRequestBody); |
| | | // 处理解密后的请求体 CustomRequestWrapper为自定义请求包装器,请看下面实现 |
| | | CustomRequestWrapper customRequestWrapper = new CustomRequestWrapper(httpRequest, decryptedRequestBody); |
| | | |
| | |
| | | |
| | | // 获取并加密响应内容 |
| | | byte[] content = responseWrapper.getContentAsByteArray(); |
| | | String originalResponseBody = new String(content); |
| | | String originalResponseBody = new String(content, StandardCharsets.UTF_8); // 关键修改 |
| | | String encryptedResponseBody = encryptResponse(originalResponseBody); |
| | | |
| | | responseWrapper.setContentType("application/json"); |
| | |
| | | * @throws IOException 如果读取或解密过程中发生错误 |
| | | */ |
| | | private String decryptRequest(HttpServletRequest request) throws IOException { |
| | | // 先设置编码 |
| | | request.setCharacterEncoding("UTF-8"); |
| | | |
| | | // 使用Reader读取,但确保使用了正确的编码 |
| | | StringBuilder jb = new StringBuilder(); |
| | | String line; |
| | | BufferedReader reader = request.getReader(); |
| | | while ((line = reader.readLine()) != null) { |
| | | jb.append(line); |
| | | // 直接使用getReader(),此时应该使用UTF-8 |
| | | try (BufferedReader reader = request.getReader()) { |
| | | while ((line = reader.readLine()) != null) { |
| | | jb.append(line); |
| | | } |
| | | } |
| | | |
| | | String requestBody = jb.toString(); |
| | | try { |
| | | return Sm4Utils.sm4DecryptUtil(jb.toString()); |
| | | return Sm4Utils.sm4DecryptUtil(requestBody); |
| | | } catch (Exception e) { |
| | | throw new ServerException("参数解密失败:{}", e); |
| | | logger.error("参数解密失败,原始数据:{}", requestBody); |
| | | throw new ServerException("参数解密失败", e); |
| | | } |
| | | } |
| | | |