springboot中request和response的加解密实现代码
作者:ldcaws 发布时间:2023-05-27 16:46:27
标签:springboot,request,response,加解密
在系统开发中,需要对请求和响应分别拦截下来进行解密和加密处理,在springboot中提供了RequestBodyAdviceAdapter和ResponseBodyAdvice,利用这两个工具可以非常方便的对请求和响应进行预处理。
1、新建一个springboot工程,pom依赖如下
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
2、自定义加密、解密的注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Encrypt {
}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.PARAMETER})
public @interface Decrypt {
}
其中加密注解放在方法上,解密注解可以放在方法上,也可以放在参数上。
3、加密算法
定义一个加密工具类,加密算法分为对称加密和非对称加密,本次使用java自带的Ciphor来实现对称加密,使用AES算法,如下
public class AESUtils {
private static final String AES_ALGORITHM = "AES/ECB/PKCS5Padding";
private static final String key = "1234567890abcdef";
/**
* 获取 cipher
* @param key
* @param model
* @return
* @throws Exception
*/
private static Cipher getCipher(byte[] key, int model) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
cipher.init(model, secretKeySpec);
return cipher;
}
/**
* AES加密
* @param data
* @param key
* @return
* @throws Exception
*/
public static String encrypt(byte[] data, byte[] key) throws Exception {
Cipher cipher = getCipher(key, Cipher.ENCRYPT_MODE);
return Base64.getEncoder().encodeToString(cipher.doFinal(data));
}
/**
* AES解密
* @param data
* @param key
* @return
* @throws Exception
*/
public static byte[] decrypt(byte[] data, byte[] key) throws Exception {
Cipher cipher = getCipher(key, Cipher.DECRYPT_MODE);
return cipher.doFinal(Base64.getDecoder().decode(data));
}
}
其中加密后的数据使用Base64算法进行编码,获取可读字符串;解密的输入也是一个Base64编码之后的字符串,先进行解码再进行解密。
4、对请求数据进行解密处理
@EnableConfigurationProperties(KeyProperties.class)
@ControllerAdvice
public class DecryptRequest extends RequestBodyAdviceAdapter {
@Autowired
private KeyProperties keyProperties;
/**
* 该方法用于判断当前请求,是否要执行beforeBodyRead方法
*
* @param methodParameter handler方法的参数对象
* @param targetType handler方法的参数类型
* @param converterType 将会使用到的Http消息转换器类类型
* @return 返回true则会执行beforeBodyRead
*/
@Override
public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
return methodParameter.hasMethodAnnotation(Decrypt.class) || methodParameter.hasParameterAnnotation(Decrypt.class);
}
/**
* 在Http消息转换器执转换,之前执行
* @param inputMessage
* @param parameter
* @param targetType
* @param converterType
* @return 返回 一个自定义的HttpInputMessage
* @throws IOException
*/
@Override
public HttpInputMessage beforeBodyRead(final HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
byte[] body = new byte[inputMessage.getBody().available()];
inputMessage.getBody().read(body);
try {
byte[] keyBytes = keyProperties.getKey().getBytes();
byte[] decrypt = AESUtils.decrypt(body, keyBytes);
final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(decrypt);
return new HttpInputMessage() {
@Override
public InputStream getBody() throws IOException {
return byteArrayInputStream;
}
@Override
public HttpHeaders getHeaders() {
return inputMessage.getHeaders();
}
};
} catch (Exception e) {
e.printStackTrace();
}
return super.beforeBodyRead(inputMessage, parameter, targetType, converterType);
}
}
5、对响应数据进行加密处理
@EnableConfigurationProperties(KeyProperties.class)
@ControllerAdvice
public class EncryptResponse implements ResponseBodyAdvice<RespBean> {
private ObjectMapper objectMapper = new ObjectMapper();
@Autowired
private KeyProperties keyProperties;
/**
* 该方法用于判断当前请求的返回值,是否要执行beforeBodyWrite方法
*
* @param methodParameter handler方法的参数对象
* @param converterType 将会使用到的Http消息转换器类类型
* @return 返回true则会执行beforeBodyWrite
*/
@Override
public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> converterType) {
return methodParameter.hasMethodAnnotation(Encrypt.class);
}
/**
* 在Http消息转换器执转换,之前执行
* @param body
* @param returnType
* @param selectedContentType
* @param selectedConverterType
* @param request
* @param response
* @return 返回 一个自定义的HttpInputMessage,可以为null,表示没有任何响应
*/
@Override
public RespBean beforeBodyWrite(RespBean body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
byte[] keyBytes = keyProperties.getKey().getBytes();
try {
if (body.getMsg() != null) {
body.setMsg(AESUtils.encrypt(body.getMsg().getBytes(), keyBytes));
}
if (body.getObj() != null) {
body.setObj(AESUtils.encrypt(objectMapper.writeValueAsBytes(body.getObj()), keyBytes));
}
} catch (Exception e) {
e.printStackTrace();
}
return body;
}
}
6、加解密的key的配置类,从配置文件中读取
@ConfigurationProperties(prefix = "spring.encrypt")
public class KeyProperties {
private final static String DEFAULT_KEY = "1234567890abcdef";
private String key = DEFAULT_KEY;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
}
7、测试
application中的key配置
spring.encrypt.key=1234567890abcdef
@GetMapping("/user")
@Encrypt
public RespBean getUser() {
User user = new User();
user.setId(1L);
user.setUsername("caocao");
return RespBean.ok("ok", user);
}
@PostMapping("/user")
public RespBean addUser(@RequestBody @Decrypt User user) {
System.out.println("user = " + user);
return RespBean.ok("ok", user);
}
测试结果
其中get请求的接口使用了@Encrypt注解,对响应数据进行了加密处理;post请求的接口使用了@Decrypt注解作用在参数上,对请求数据进行了解密处理。
来源:https://blog.csdn.net/leijie0322/article/details/125147633


猜你喜欢
- 前言1.因为涉及到对象锁,Wait、Notify一定要在synchronized里面进行使用。2.Wait必须暂定当前正在执行的线程,并释放
- 实例:用户输入一个日期,要求输出这个日期是星期几和在这一年中的第几天://声明一个DateTime类型的变量用于存放用户输入的日期DateT
- maven打包方式使用maven打包插件maven-jar-plugin在pom.xml文件最后新增以下代码。maven-dependenc
- 一般我们在controller层调用service时,只需要使用@Autowired注解即可,例如如下代码我们经常看到:@RestContr
- 本文实例讲述了C#中的事务用法。分享给大家供大家参考。具体如下:直接用SQL语句创建事务, 当然不是什么稀奇事了, 好是好, 只是麻烦.看看
- 本文实例为大家分享了android实现简单活动转盘的具体代码,供大家参考,具体内容如下页面public class CircleTurnta
- 基于servlet+jsp+jdbc的后台管理系统,包含5个模块:汽车账户部管理、租车账户部管理、汽车信息管理表、租车记录表、租车租聘表。功
- 当把一个事件发布到Spring提供的ApplicationContext中,被 * 侦测到,就会执行对应的处理方法。事件本身事件是一个自定义
- 前言最近因为同事bean配置的问题导致生产环境往错误的redis实例写入大量的数据,差点搞挂redis。经过快速的问题定位,发现是同事新增一
- 本文我将要介绍一下mybatis的框架原理,以及mybatis的入门程序,实现用户的增删改查,她有什么优缺点以及mybatis和hibern
- 一、概述本质上,这是一个包含有可选值的包装类,这意味着 Optional 类既可以含有对象也可以为空。Optional 是 Java 实现函
- 开发 Web 应用的思路实现一个简单的 JSP/Servlet。搭建创建 Web 应用工程的环境。创建 Web 应用工程。Web 应用工程的
- 本文为大家分享了JAVA语言课程设计:连连看小游戏,供大家参考,具体内容如下1.设计内容界面中有5*10的界面,图中共有6种不同的图片,每两
- 本文实例为大家分享了C#获取计算机信息的具体代码,供大家参考,具体内容如下using System;using System.Configu
- 本文实例讲述了Android基于DialogFragment创建对话框的方法。分享给大家供大家参考,具体如下:/** * 使用DialogF
- 在javaweb中写了一个图片的链接,可以打开预览,另外提供一个下载功能。以下是预览代码,没什么好说的;href若连接的是一个压缩包文件之类
- 本文简单分析了C/C++中常用函数的易错点,包括memset、sizeof、getchar等函数。分享给大家供大家参考之用。具体分析如下:1
- 刚开始项目,需要用到mybatis分页,网上看了很多插件,其实实现原理基本都大同小异,但是大部分都只给了代码,注释不全,所以参考了很多篇文章
- 一、字符串:1、访问String中的字符:string本身可看作一个Char数组。string s = "hello world&
- 本文实例为大家分享了Android实现滑动标尺选择值,效果图1.自定义属性attrs.xml<declare-styleable na