栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java > SpringBoot

使用RequestBodyAdvice处理客户端的加密请求体

SpringBoot 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用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 {

	
	boolean supports(MethodParameter methodParameter, Type targetType,
			Class> converterType);

	
	HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter,
			Type targetType, Class> converterType) throws IOException;

	
	Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter,
			Type targetType, Class> converterType);

	
	@Nullable
	Object handleEmptyBody(@Nullable Object body, HttpInputMessage inputMessage, MethodParameter parameter,
			Type targetType, Class> 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> converterType)
			throws IOException {

		return inputMessage;
	}

	@Override
	public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter,
			Type targetType, Class> converterType) {

		return body;
	}

	@Override
	@Nullable
	public Object handleEmptyBody(@Nullable Object body, HttpInputMessage inputMessage,
			MethodParameter parameter, Type targetType,
			Class> 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 {

	
	private static final byte[] AES_KEY = "1111111111111111".getBytes(StandardCharsets.US_ASCII);

	@Override
	public boolean supports(MethodParameter methodParameter, Type targetType,
			Class> converterType) {
		
		return GsonHttpMessageConverter.class.isAssignableFrom(converterType);
	}

	@Override
	public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
			Class> 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;
			}
		};
	}

	
	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

转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号