springboot中request和response的加解密實(shí)現(xiàn)代碼
在系統(tǒng)開發(fā)中,需要對(duì)請(qǐng)求和響應(yīng)分別攔截下來進(jìn)行解密和加密處理,在springboot中提供了RequestBodyAdviceAdapter和ResponseBodyAdvice,利用這兩個(gè)工具可以非常方便的對(duì)請(qǐng)求和響應(yīng)進(jìn)行預(yù)處理。
1、新建一個(gè)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 {
}其中加密注解放在方法上,解密注解可以放在方法上,也可以放在參數(shù)上。
3、加密算法
定義一個(gè)加密工具類,加密算法分為對(duì)稱加密和非對(duì)稱加密,本次使用java自帶的Ciphor來實(shí)現(xiàn)對(duì)稱加密,使用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));
}
}
其中加密后的數(shù)據(jù)使用Base64算法進(jìn)行編碼,獲取可讀字符串;解密的輸入也是一個(gè)Base64編碼之后的字符串,先進(jìn)行解碼再進(jìn)行解密。
4、對(duì)請(qǐng)求數(shù)據(jù)進(jìn)行解密處理
@EnableConfigurationProperties(KeyProperties.class)
@ControllerAdvice
public class DecryptRequest extends RequestBodyAdviceAdapter {
@Autowired
private KeyProperties keyProperties;
/**
* 該方法用于判斷當(dāng)前請(qǐng)求,是否要執(zhí)行beforeBodyRead方法
*
* @param methodParameter handler方法的參數(shù)對(duì)象
* @param targetType handler方法的參數(shù)類型
* @param converterType 將會(huì)使用到的Http消息轉(zhuǎn)換器類類型
* @return 返回true則會(huì)執(zhí)行beforeBodyRead
*/
@Override
public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
return methodParameter.hasMethodAnnotation(Decrypt.class) || methodParameter.hasParameterAnnotation(Decrypt.class);
}
/**
* 在Http消息轉(zhuǎn)換器執(zhí)轉(zhuǎn)換,之前執(zhí)行
* @param inputMessage
* @param parameter
* @param targetType
* @param converterType
* @return 返回 一個(gè)自定義的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、對(duì)響應(yīng)數(shù)據(jù)進(jìn)行加密處理
@EnableConfigurationProperties(KeyProperties.class)
@ControllerAdvice
public class EncryptResponse implements ResponseBodyAdvice<RespBean> {
private ObjectMapper objectMapper = new ObjectMapper();
@Autowired
private KeyProperties keyProperties;
/**
* 該方法用于判斷當(dāng)前請(qǐng)求的返回值,是否要執(zhí)行beforeBodyWrite方法
*
* @param methodParameter handler方法的參數(shù)對(duì)象
* @param converterType 將會(huì)使用到的Http消息轉(zhuǎn)換器類類型
* @return 返回true則會(huì)執(zhí)行beforeBodyWrite
*/
@Override
public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> converterType) {
return methodParameter.hasMethodAnnotation(Encrypt.class);
}
/**
* 在Http消息轉(zhuǎn)換器執(zhí)轉(zhuǎn)換,之前執(zhí)行
* @param body
* @param returnType
* @param selectedContentType
* @param selectedConverterType
* @param request
* @param response
* @return 返回 一個(gè)自定義的HttpInputMessage,可以為null,表示沒有任何響應(yīng)
*/
@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、測(cè)試
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);
}
測(cè)試結(jié)果


其中g(shù)et請(qǐng)求的接口使用了@Encrypt注解,對(duì)響應(yīng)數(shù)據(jù)進(jìn)行了加密處理;post請(qǐng)求的接口使用了@Decrypt注解作用在參數(shù)上,對(duì)請(qǐng)求數(shù)據(jù)進(jìn)行了解密處理。
到此這篇關(guān)于springboot中request和response的加解密實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)springboot加解密內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java實(shí)現(xiàn)經(jīng)典游戲打磚塊游戲的示例代碼
這篇文章主要介紹了如何利用Java實(shí)現(xiàn)經(jīng)典的游戲—打磚塊。玩家操作一根螢?zāi)簧纤降摹鞍糇印保屢活w不斷彈來彈去的“球”在撞擊作為過關(guān)目標(biāo)消去的“磚塊”的途中不會(huì)落到螢?zāi)坏紫?。感興趣的小伙伴可以了解一下2022-02-02
Java使用Spring發(fā)送郵件的實(shí)現(xiàn)代碼
本篇文章主要介紹了使用Spring發(fā)送郵件的實(shí)現(xiàn)代碼,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-03-03
IDEA的spring項(xiàng)目使用@Qualifier飄紅問題及解決
這篇文章主要介紹了IDEA的spring項(xiàng)目使用@Qualifier飄紅問題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-11-11
SpringBoot整合WebSocket實(shí)現(xiàn)實(shí)時(shí)通信功能
在當(dāng)今互聯(lián)網(wǎng)時(shí)代,實(shí)時(shí)通信已經(jīng)成為了許多應(yīng)用程序的基本需求,而WebSocket作為一種全雙工通信協(xié)議,為開發(fā)者提供了一種簡(jiǎn)單、高效的實(shí)時(shí)通信解決方案,本文將介紹如何使用SpringBoot框架來實(shí)現(xiàn)WebSocket的集成,快速搭建實(shí)時(shí)通信功能,感興趣的朋友可以參考下2023-11-11
eclipse創(chuàng)建java項(xiàng)目并運(yùn)行的詳細(xì)教程講解
eclipse是java開發(fā)的ide工具,是大部分java開發(fā)人員的首選開發(fā)工具,可是對(duì)于一些新Java人員來說,不清楚eclipse怎么運(yùn)行項(xiàng)目?這篇文章主要給大家介紹了關(guān)于eclipse創(chuàng)建java項(xiàng)目并運(yùn)行的相關(guān)資料,需要的朋友可以參考下2023-04-04

