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
0
投稿
猜你喜欢
- Java main 方法面试题的详细整理1.不用main方法如何定义一个类?不行,没有main方法我们不能运行Java类。在java 7之前
- Note:这篇文章是基于Android Studio 3.01版本的,NDK是R16。step1:创建一个包含C++的项目其他默认就可以了。
- Eureka 采用 CS(Client/Server,客户端/服务器) 架构,它包括以下两大组件:Eureka Server:Eureka
- 登录注册小代码,将学过的一些小知识融合在一起进行了使用,加深印象。本例中如果有注释不详细的地方,详见其它博客。功能介绍:简单的登录注册系统,
- 1.内部类概念及分类将一个类定义在另一个类的内部或者接口内部或者方法体内部,这个类就被称为内部类,我们不妨将内部类所在的类称为外围类,除了定
- 最好使用英文,不要用汉语拼音1:包(package):用于将完成不同功能的类分门别类,放在不同的目录(包)下,包的命名规则:将公司域名反转作
- 1.新建springBoot项目在前面有两种方式2.加入thymeleaf模板引擎SpringBoot推荐使用thymeleaf模板引擎语法
- 前言最常用的对字符串操作的类有三个,分别是String,StringBuilder,StringBuffer,下面将会详细的说说这三个类..
- 看一段程序String t = "a||b||c||d";String[] temp = t.split("\
- 使用@Autowired注解有错误提示使用Spring boot +mybatis框架时,在service实现类中使用Mapper类,给Ma
- 在处理大文件时,如果利用普通的FileInputStream 或者FileOutputStream 抑或RandomAccessFile 来
- 前言一般在写业务接口的过程中,很有可能需要实现可以动态组合各种查询条件的接口。如果我们根据一种查询条件组合一个方法的做法来写,那么将会有大量
- Java并发包的locks包里的锁基本上已经介绍得差不多了,ReentrantLock重入锁是个关键,在清楚的了解了同步器AQS的运行机制后
- 本文实例讲述了C#移除所有事件绑定的方法。分享给大家供大家参考。具体分析如下:private delegate int DEL_TEST_E
- Java 8中引入了CompletableFuture类,它是一种方便的异步编程工具,可以处理各种异步操作,如网络请求、文件IO和数据库操作
- 这篇文章主要介绍了基于Java检查IPv6地址的合法性,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋
- 什么是零拷贝?零拷贝(英语: Zero-copy)技术是指计算机执行操作时,CPU不需要先将数据从某处内存复制到另一个特定区域。这种技术通常
- 首先,确保 IDEA 软件正确安装完成,Java 开发工具包 JDK 安装完成。IDEA 的 Java 项目 (Project) 则相当于
- 封面图下个季度的目标是把前端监控相关的内容梳理出来,梳理出来之后可能会在公司内部做个分享~Flutter应用程序既括代码也包括一些其他的资产
- 当需要将一个对象输出到显示器时,通常要调用他的toString()方法,将对象的内容转换为字符串.java中的所有类默认都有一个toStri