zoukankan      html  css  js  c++  java
  • 使用@RequestBodyAdvice处理客户端的加密请求体

    业务场景:客户端把json数据进行加密后,编码成Base64字符串,提交给服务器。服务器再进行解密。
    使用 @RequestBodyAdvice,可以在不修改任何Controller代码的前提下,轻松完成。

    之前写过一篇帖子,使用@ResponseBodyAdvice统一对响应的数据进行处理。演示了,使用ResponseBodyAdvice统一对响应给客户的json进行AES加密。

    RequestBodyAdvice 接口

    这个接口定义了一系列的方法,它可以在请求体数据被HttpMessageConverter转换前,后。执行一些逻辑代码。通常用来做解密。

    import java.io.IOException;
    import java.lang.reflect.Type;
    
    import org.springframework.core.MethodParameter;
    import org.springframework.http.HttpInputMessage;
    import org.springframework.http.converter.HttpMessageConverter;
    import org.springframework.lang.Nullable;
    
    public interface RequestBodyAdvice {
    
    	/**
    	 * 该方法用于判断当前请求,是否要执行beforeBodyRead方法
    	 * @param handler方法的参数对象
    	 * @param handler方法的参数类型
    	 * @param 将会使用到的Http消息转换器类类型
    	 * @return 返回true则会执行beforeBodyRead
    	 */
    	boolean supports(MethodParameter methodParameter, Type targetType,
    			Class<? extends HttpMessageConverter<?>> converterType);
    
    	/**
    	 * 在Http消息转换器执转换,之前执行 
    	 * @param 客户端的请求数据
    	 * @param handler方法的参数对象
    	 * @param handler方法的参数类型
    	 * @param 将会使用到的Http消息转换器类类型
    	 * @return 返回 一个自定义的HttpInputMessage 
    	 */
    	HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter,
    			Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException;
    
    	/**
    	 * 在Http消息转换器执转换,之后执行 
    	 * @param 转换后的对象
    	 * @param 客户端的请求数据
    	 * @param handler方法的参数类型
    	 * @param handler方法的参数类型
    	 * @param 使用的Http消息转换器类类型
    	 * @return 返回一个新的对象
    	 */
    	Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter,
    			Type targetType, Class<? extends HttpMessageConverter<?>> converterType);
    
    	/**
    	 * 同上,不过这个方法处理的是,body为空的情况
    	 */
    	@Nullable
    	Object handleEmptyBody(@Nullable Object body, HttpInputMessage inputMessage, MethodParameter parameter,
    			Type targetType, Class<? extends HttpMessageConverter<?>> converterType);
    
    
    }
    

    核心的方法就是 supports,该方法返回的boolean值,决定了是要执行 beforeBodyRead 方法。而我们主要的逻辑就是在beforeBodyRead方法中,对客户端的请求体进行解密。

    RequestBodyAdviceAdapter

    实现 RequestBodyAdvice 接口的适配器抽象类

    import java.io.IOException;
    import java.lang.reflect.Type;
    
    import org.springframework.core.MethodParameter;
    import org.springframework.http.HttpInputMessage;
    import org.springframework.http.converter.HttpMessageConverter;
    import org.springframework.lang.Nullable;
    
    public abstract class RequestBodyAdviceAdapter implements RequestBodyAdvice {
    	@Override
    	public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter,
    			Type targetType, Class<? extends HttpMessageConverter<?>> converterType)
    			throws IOException {
    
    		return inputMessage;
    	}
    
    	@Override
    	public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter,
    			Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
    
    		return body;
    	}
    
    	@Override
    	@Nullable
    	public Object handleEmptyBody(@Nullable Object body, HttpInputMessage inputMessage,
    			MethodParameter parameter, Type targetType,
    			Class<? extends HttpMessageConverter<?>> converterType) {
    
    		return body;
    	}
    
    }
    
    

    演示:解密客户端的AES加密请求体

    客户端使用AES算法把json数据使用AES(128位密钥)加密后,编码为Base64字符串作为请求体,请求服务器。服务器在 RequestBodyAdvice中完成解密。

    RequestBodyDecodeAdvice

    import java.io.ByteArrayInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.lang.reflect.Type;
    import java.nio.charset.StandardCharsets;
    import java.security.InvalidKeyException;
    import java.security.NoSuchAlgorithmException;
    import java.util.Base64;
    
    import javax.crypto.BadPaddingException;
    import javax.crypto.Cipher;
    import javax.crypto.IllegalBlockSizeException;
    import javax.crypto.NoSuchPaddingException;
    import javax.crypto.spec.SecretKeySpec;
    
    import org.springframework.core.MethodParameter;
    import org.springframework.http.HttpHeaders;
    import org.springframework.http.HttpInputMessage;
    import org.springframework.http.converter.HttpMessageConverter;
    import org.springframework.http.converter.json.GsonHttpMessageConverter;
    import org.springframework.web.bind.annotation.RestControllerAdvice;
    import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdviceAdapter;
    
    @RestControllerAdvice
    public class RequestBodyDecodeAdvice extends RequestBodyAdviceAdapter {
    
    	/**
    	 * 128位的AESkey
    	 */
    	private static final byte[] AES_KEY = "1111111111111111".getBytes(StandardCharsets.US_ASCII);
    
    	@Override
    	public boolean supports(MethodParameter methodParameter, Type targetType,
    			Class<? extends HttpMessageConverter<?>> converterType) {
    		/**
    		 * 系统使用的是Gson作为json数据的Http消息转换器
    		 */
    		return GsonHttpMessageConverter.class.isAssignableFrom(converterType);
    	}
    
    	@Override
    	public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
    			Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
    
    		// 读取加密的请求体
    		byte[] body = new byte[inputMessage.getBody().available()];
    		inputMessage.getBody().read(body);
    
    		try {
    			// 使用AES解密
    			body = this.decrypt(Base64.getDecoder().decode(body), AES_KEY);
    		} catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException
    				| BadPaddingException e) {
    			e.printStackTrace();
    			throw new RuntimeException(e);
    		}
    
    		// 使用解密后的数据,构造新的读取流
    		InputStream rawInputStream = new ByteArrayInputStream(body);
    		return new HttpInputMessage() {
    			@Override
    			public HttpHeaders getHeaders() {
    				return inputMessage.getHeaders();
    			}
    
    			@Override
    			public InputStream getBody() throws IOException {
    				return rawInputStream;
    			}
    		};
    	}
    
    	/**
    	 * AES解密
    	 * 
    	 * @param data
    	 * @param key
    	 * @return
    	 * @throws InvalidKeyException
    	 * @throws NoSuchAlgorithmException
    	 * @throws NoSuchPaddingException
    	 * @throws IllegalBlockSizeException
    	 * @throws BadPaddingException
    	 */
    	public byte[] decrypt(byte[] data, byte[] key) throws InvalidKeyException, NoSuchAlgorithmException,
    			NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
    		Cipher cipher = getCipher(key, Cipher.DECRYPT_MODE);
    		return cipher.doFinal(data);
    	}
    
    	private Cipher getCipher(byte[] key, int model)
    			throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
    		SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
    		Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    		cipher.init(model, secretKeySpec);
    		return cipher;
    	}
    }
    
    

    TestController

    很简单,几乎没有任何改动,只是打印客户的的请求体

    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import com.google.gson.JsonObject;
    
    @RestController
    @RequestMapping("/test")
    public class TestController {
    	
    	private static final Logger LOGGER = LoggerFactory.getLogger(TestController.class);
    	
    	@PostMapping
    	public Object test (@RequestBody JsonObject requestBody) {
    		LOGGER.info("requestBody={}", requestBody);
    		return requestBody;
    	}
    }
    
    

    客户端

    使用相同的AES密钥加密原始数据


    加密后的Base64编码

    Gg/hLfWllxXF7KkzeNTPELCZ3jjxgHL24tJWPhO+O7KS5vAS1ag9xmtjP94L8p8BY+HMggCL1mvVEHEL8+FwSSjWYLln8SZk4CuWil2x4sI=
    

    使用Postman发起请求

    服务器响应的就是解密后的请求体

    服务器日志

    2020-07-22 13:39:31.870  INFO 2684 --- [  XNIO-1 task-1] TestController    : requestBody={"name":"SpringBoot中文社区","site":"https://springboot.io"}
    
    

    成功的解密了数据,并且完成了json对象的编码。

    原文: https://springboot.io/t/topic/2266

  • 相关阅读:
    nginx下根据指定路由重定向
    Ubuntu下配置apache开启https
    php+websocket搭建简易聊天室实践
    rsync + git发布项目
    nginx下配置Yii2 rewrite、pathinfo等
    新装NGINX重启,出现错误 nginx: [error] open() "/usr/local/nginx/logs/nginx.pid"
    wamp mysql服务意外停止
    PHP异步请求
    php curl_errno 60
    php开启fileinfo扩展
  • 原文地址:https://www.cnblogs.com/kevinblandy/p/13360221.html
Copyright © 2011-2022 走看看