package jnpf.encrypt; import cn.hutool.core.util.HexUtil; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import jnpf.annotation.EncryptApi; import jnpf.properties.SecurityProperties; import jnpf.util.DesUtil; 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.web.bind.annotation.ControllerAdvice; import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice; @ControllerAdvice public class EncryptResponseAdvice implements ResponseBodyAdvice { private ObjectMapper objectMapper; public EncryptResponseAdvice(ObjectMapper objectMapper) { this.objectMapper = objectMapper; } @Override public boolean supports(MethodParameter returnType, Class> converterType) { EncryptApi methodAnnotation = returnType.getMethodAnnotation(EncryptApi.class); return methodAnnotation != null && methodAnnotation.encryptResponse(); } @Override public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) { try { byte[] bytes = objectMapper.writeValueAsBytes(body); return HexUtil.encodeHexStr(DesUtil.aesOrDecode(bytes, true, true, SecurityProperties.getInstance().getSecurityKey())); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } }