Springboot框架,实现请求数据解密,响应数据加密的功能。
一、简要说明:
在做这个功能的时候,参考了很多文章,也试了用过滤器解决。但总体来说还是很麻烦,所以换了另一种解决方案。直接实现RequestBodyAdvice和ResponseBodyAdvice两个接口 ,进行加密解密处理。
关于RequestBodyAdvice和ResponseBodyAdvice接口的作用,可参考该文档:
(1)https://blog.csdn.net/qq_16504067/article/details/73225005
(2) https://blog.csdn.net/jing956899449/article/details/54315048
二、解密 DecodeRequestBodyAdvice
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;
import lombok.extern.slf4j.Slf4j;
@Component
@ControllerAdvice(basePackages = "com.kiki.controller")
@Slf4j
public class DecodeRequestBodyAdvice implements RequestBodyAdvice { @Override
public boolean supports(MethodParameter methodParameter, Type targetType,
Class<? extends HttpMessageConverter<?>> converterType) {
//这里设置成false 它就不会再走这个类了
return true;
}
@Override
public HttpInputMessage beforeBodyRead(HttpInputMessage request, MethodParameter parameter, Type targetType,
Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = null;
try {
//这个request其实就是入参 可以从这里获取流
//入参放在HttpInputMessage里面 这个方法的返回值也是HttpInputMessage
InputStream inputStream = request.getBody();
if (inputStream != null) {
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
char[] charBuffer = new char[128];
int bytesRead = -1;
while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
stringBuilder.append(charBuffer, 0, bytesRead);
}
} else {
stringBuilder.append("");
}
} catch (IOException ex) {
throw ex;
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException ex) {
throw ex;
}
}
}
//获取请求数据
String string = stringBuilder.toString();
/*****************进行解密start*******************/
log.info("【接受的请求数据】string={}",string); String decode =Base64Utils.decode(string);
log.info("【解密后的请求数据】decode={}",decode); //把数据放到我们封装的对象中
return new MyHttpInputMessage(request.getHeaders(), new ByteArrayInputStream(decode.getBytes("UTF-8")));
} @Override
public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
Class<? extends HttpMessageConverter<?>> converterType) {
return body;
} @Override
public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter,
Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
return body;
}
//这里实现了HttpInputMessage 封装一个自己的HttpInputMessage
static class MyHttpInputMessage implements HttpInputMessage {
HttpHeaders headers;
InputStream body; public MyHttpInputMessage(HttpHeaders headers, InputStream body) {
this.headers = headers;
this.body = body;
} @Override
public InputStream getBody() throws IOException {
return body;
} @Override
public HttpHeaders getHeaders() {
return headers;
}
} }
三、加密 EncodeResponseBodyAdvice
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
@Component
@ControllerAdvice(basePackages = "com.kiki.controller")
@Slf4j
public class EncodeResponseBodyAdvice implements ResponseBodyAdvice<Object> { @Override
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
return true;
} @Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
ServerHttpResponse response) {
System.out.println("response-------->"+body);
//加密
log.info("【接受到的数据】encode={}",body);
String encode = Base64Utils.encode(JSON.toJSONString(body));
return encode;
} }
四、工具类
import java.nio.charset.StandardCharsets;
import java.util.Base64; public class Base64Utils {
/**
* 使用Base64加密字符串
* @return 加密之后的字符串
*
*/
public static String encode(String data){
return Base64.getEncoder().encodeToString(data.getBytes(StandardCharsets.UTF_8));
}
/**
* 使用Base64解密
* @return 解密之后的字符串
*
*/
public static String decode(String data){
return new String(Base64.getDecoder().decode(data.replace("\"", "")),StandardCharsets.UTF_8);
}
public static void main(String[] args) {
String encode = encode("{\"key\":\"kiki123\",\"value\":\"hello lmbx\"}");
System.out.println(encode);
String decode = decode("eyJrZXkiOiIxMjMiLCJ2YWx1ZSI6ImFhYSJ9");
System.out.println(decode); }
}
五、bean
import lombok.Data; @Data
public class DataBean {
private String key;
private String value;
}
六、Controller
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.kiki.bean.DataBean;
@RestController
@RequestMapping("/api/")
public class DataController {
@PostMapping("test")
public DataBean test(@RequestBody DataBean dataBean) {
System.out.println("controller::::"+dataBean);
dataBean.setKey("456");
dataBean.setValue("0000");
return dataBean;
}
}
Springboot框架,实现请求数据解密,响应数据加密的功能。的更多相关文章
- SpringBoot web获取请求数据【转】
SpringBoot web获取请求数据 一个网站最基本的功能就是匹配请求,获取请求数据,处理请求(业务处理),请求响应,我们今天来看SpringBoot中怎么获取请求数据. 文章包含的内容如下: 获 ...
- spring mvc 通过拦截器记录请求数据和响应数据
spring mvc 能过拦截器记录请求数据记录有很多种方式,主要有以下三种: 1:过滤器 2:HandlerInterceptor拦截器 3:Aspect接口控制器 但是就我个人所知要记录返回的数据 ...
- idea模拟前端向后台请求数据输出响应结果
tools-httpClient-Test restful web service 通过上述步骤之后出现如下图 1 表示通过哪种方式请求:2 请求数据的地址头部:3 请求数据的除了头部之后的地址:4, ...
- Asp.net MVC Vue Axios无刷新请求数据和响应数据
Model层Region.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; ...
- SpringBoot学习之Json数据交互
最近在弄监控主机项目,对javaweb又再努力学习.实际的项目场景中,前后分离几乎是所以项目的标配,全栈的时代的逐渐远去,后端负责业务逻辑处理,前端负责数据展示成了一种固定的开发模式.像thymele ...
- Spring对JSON请求加解密
Spring中处理JSON请求通常使用@RequestBody和@ResponseBody注解,针对JSON请求加解密和过滤字符串,Spring提供了RequestBodyAdvice和Respons ...
- Fiddler插件 --- 解密Elong Mapi请求参数及响应内容
当前问题: 在我们日常的Web/App测试过程中, Fiddler是一大辅助利器:在我们团队,也经常使用Fiddler进行App抓包测试. 艺龙 App使用的REST(内部称为Mapi)接口,在使用过 ...
- SpringBoot框架中,使用过滤器进行加密解密操作(一)
一.基本说明 1.请求方式:POST请求.注解@PostMapping 2.入参格式:json串 3.出参格式:json串(整体加密) 4.使用Base64进行加密解密.具体的加密方式,可以根据需求自 ...
- SpringMVC请求参数和响应结果全局加密和解密
前提 前段时间在做一个对外的网关项目,涉及到加密和解密模块,这里详细分析解决方案和适用的场景.为了模拟真实的交互场景,先定制一下整个交互流程.第三方传输(包括请求和响应)数据报文包括三个部分: 1.t ...
随机推荐
- 算法和数据结构~各位排序算法的介绍与实现(C#)
排序是指将元素集合按照规定的顺序排列.通常有两种排序方法,升序排列和降序排列.例如,对整数集{5,2,7,1}进行升序排列,结果为{1,2,5,7},对其进行降序排列结果为{7,5,2,1}.总的来说 ...
- Linux c获取任意路径的硬盘使用情况
没有什么好说的,其实就是获取硬盘的statfs信息结构 代码如下: #include <stdio.h> #include <stdlib.h> #include <sy ...
- 给listview加动画,让动画执行结束后再刷新
问题:当给listview的条目加动画时,例如添加一个条目或者移除一个条目,动画效果会和添加删除条目的逻辑同时进行,因为动画并不是阻塞式的,这样会造成动画还没有结束,条目已经添加或者移除,从而动画作用 ...
- vue+uwsgi+nginx部署前后端分离项目
前后端分离,vue前端提供静态页面,且可以向后台发起get,post等restful请求. django后台提供数据支撑,返回json数据,返回给vue,进行数据页面渲染 后端 创建虚拟环境 解决dj ...
- springboot使用redisTemplate遇到的问题
概述 最近工作中新构建了一个项目,用的springboot,由于项目中要使用各种各样的缓存,就使用了spring-data-redis,这个东西比我想象中要难使用的多啊,而且我还遇到个问题,就是在用R ...
- angular $resouse服务
创建服务 var taskInstancesResource = function ($resource) { var resource = $resource('/ssc-cutover/rest/ ...
- Docker环境下的Mysql8 实现主从数据库数据同步方案
本文记录下通过MySQL Replication在Docker环境下,通过多个容器 实现数据库主从配置. MySQL Replication就不多解释了,简单说就是MySQL非常出色的一个功能,该功能 ...
- vue学习笔记——篇3
1.绑定计算后数据,三种方式: >1.红色框,通过method >2.黄色框,通过computed >3.蓝色框,通过watch 推荐computed,vue对computed做了缓 ...
- Beta冲刺 6
前言 队名:拖鞋旅游队 组长博客:https://www.cnblogs.com/Sulumer/p/10129063.html 作业博客:https://edu.cnblogs.com/campus ...
- TCP端口检测工具
很多时候,我们需要测试 tcp 端口.ping 命令虽然好用,但不能测试端口,因为 ping 基于ICMP协议,属于IP层协议,所以无法测试传输层的 TCP/UDP 端口.幸好有tcping命令,可以 ...