EncryptResponseAdvice.java 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package jnpf.encrypt;
  2. import cn.hutool.core.util.HexUtil;
  3. import com.fasterxml.jackson.core.JsonProcessingException;
  4. import com.fasterxml.jackson.databind.ObjectMapper;
  5. import jnpf.annotation.EncryptApi;
  6. import jnpf.properties.SecurityProperties;
  7. import jnpf.util.DesUtil;
  8. import org.springframework.core.MethodParameter;
  9. import org.springframework.http.MediaType;
  10. import org.springframework.http.converter.HttpMessageConverter;
  11. import org.springframework.http.server.ServerHttpRequest;
  12. import org.springframework.http.server.ServerHttpResponse;
  13. import org.springframework.web.bind.annotation.ControllerAdvice;
  14. import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
  15. @ControllerAdvice
  16. public class EncryptResponseAdvice implements ResponseBodyAdvice<Object> {
  17. private ObjectMapper objectMapper;
  18. public EncryptResponseAdvice(ObjectMapper objectMapper) {
  19. this.objectMapper = objectMapper;
  20. }
  21. @Override
  22. public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
  23. EncryptApi methodAnnotation = returnType.getMethodAnnotation(EncryptApi.class);
  24. return methodAnnotation != null && methodAnnotation.encryptResponse();
  25. }
  26. @Override
  27. public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
  28. try {
  29. byte[] bytes = objectMapper.writeValueAsBytes(body);
  30. return HexUtil.encodeHexStr(DesUtil.aesOrDecode(bytes, true, true, SecurityProperties.getInstance().getSecurityKey()));
  31. } catch (JsonProcessingException e) {
  32. throw new RuntimeException(e);
  33. }
  34. }
  35. }