Be implemented in spring and ResponseBodyAdvice parameter based on encryption and decryption RequestBodyAdvice

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https: //blog.csdn.net/fu_huo_1993/article/details/88350186
    in the daily development, and sometimes we often need to deal with third-party interfaces, sometimes we call someone else's third-party interfaces, sometimes others call our third party interface, in order to invoke the security of interfaces, usually on the transmitted data encryption, if we go by each interface to manually encrypt and decrypt, then the heavy workload and the code redundancy . Is there a simple way to provide aid RequestBodyAdvice and ResponseBodyAdvice spring can achieve encryption and decryption operations.

Requirements:
     1, the background method if @Encrypt notes and @RequestBody modified approach needs to be decrypted parameters    

     2, the background method if @Encrypt notes and @ResponseBody modified approach that requires encryption parameters

     3, encryption and decryption rules

           Encryption: -encrypt value increases the value returned

           Decryption: Delete -encrypt value of the incoming values

     Note:

          1, @ Encrypt is a custom annotation.

          2, here for simplicity, use the delete or add -encrypt this, the actual circumstances may use sophisticated encryption and decryption rules

Pre-knowledge:
RequestBodyAdvice: in sping 4.2 added a new interface that can be used before or @RequestBody HttpEntity modified parameters for processing parameters, such as decrypting parameters.

ResponseBodyAdvice: spring 4.1 in a newly added interface before the message body is allowed to write the Controller HttpMessageConverter @ResponseBody ResponseEntity modified method to adjust the content of the response, such as the corresponding encrypted.

Functions to achieve:
1, class notes written encryption (Encrypt)

/ **
 * encryption and decryption parameters
 *
 * @author huan.fu
 * @date 2018/9/28 - 16:08
 * /
@Target ({ElementType.PARAMETER, ElementType.METHOD})
@Retention (RetentionPolicy.RUNTIME)
@Documented
public @interface Encrypt {
}
 2, write RequestBodyAdvice interface class that implements the decryption of operational data

 

/**
 * 解密数据
 *
 * @author huan.fu
 * @date 2018/9/28 - 16:09
 */
@Slf4j
@RestControllerAdvice
public class ParamEncryptRequestBodyAdvice implements RequestBodyAdvice {
 
    @Override
    public boolean supports(MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return methodParameter.hasParameterAnnotation(RequestBody.class);
    }
 
    @Override
    public Object handleEmptyBody(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return o;
    }
 
    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) throws IOException {
        return new HttpInputMessage() {
            @Override
            public InputStream getBody() throws IOException {
                log.info("此处进行解密数据");
                return new ByteArrayInputStream(IOUtils.toString(httpInputMessage.getBody()).replace("-encrypt", "").getBytes(StandardCharsets.UTF_8));
            }
 
            @Override
            public HttpHeaders getHeaders() {
                return httpInputMessage.getHeaders();
            }
        };
    }
 
    @Override
    public Object afterBodyRead (?? Object O, HttpInputMessage httpInputMessage, MethodParameter MethodParameter, the Type type, Class <the extends HttpMessageConverter types <>> aClass) {
        return O;
    }
}
 . 3, prepared ResponseBodyAdvice class interface, data encryption operation

/**
 * 加密数据
 *
 * @author huan.fu
 * @date 2018/9/28 - 16:19
 */
@Slf4j
@RestControllerAdvice
public class ParamEncryptResponseBodyAdvice implements ResponseBodyAdvice {
 
    private final ObjectMapper objectMapper = new ObjectMapper();
 
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return returnType.hasMethodAnnotation(ResponseBody.class);
    }
 
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        log.info("此处进行加密数据");
        IF (! = null body) {
            the try {
                the Map Map = objectMapper.readValue (objectMapper.writeValueAsString (body), Map.class);
                map.forEach ((Key, value) -> map.put (Key, value + "- the encrypt "));
                return Map;
            } the catch (IOException E) {
                log.error (" data encryption failure ", E);.
            }
        }
 
        return body;
    }
}
 . 4, the test write control layer

/ **
 * Controller User Information
 *
 * @author huan.fu
 * @date 2018/9/28 - 15:55
 * /
@RestController
@RequestMapping ( "User-info")
@ SLF4J
public class UserInfoController {
 
    / **
     * adding users to achieve return value of the encrypted
     *
     * @param the userInfo
     * @return
     * /
    @PostMapping ( "the Add")
    @Encrypt
    public the UserInfo the Add (@RequestBody the UserInfo the userInfo) {
        log.info ( "Add new user: [{}]", the userInfo);
        return the userInfo;
    }
 
    / **
     * modified to achieve the parameter acquisition decrypting
     *
     * @param the userInfo
     * @return
     * /
    @PostMapping ( "Update")
    public the UserInfo Update (@Encrypt @RequestBody the UserInfo the userInfo) {
        log.info ( "modify user information: [{}]", the userInfo);
        return the userInfo;
    }
}
 . 5, the decryption operation test parameters

  It can be seen that: the parameter is transmitted back -encrypt is automatically intercepted background, so similar decryption operation.

 6, the operation returns the encrypted value of the test

 Can be seen that: after the value has returned a -encrypt, thus achieving a similar encryption.


----------------
Disclaimer: This article is CSDN blogger "huan_1993 'original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement. .
Original link: https: //blog.csdn.net/fu_huo_1993/article/details/88350186

Published 51 original articles · won praise 80 · views 930 000 +

Guess you like

Origin blog.csdn.net/xiyang_1990/article/details/103093119