一、基本说明

  1.请求方式:POST请求。注解@PostMapping

  2.入参格式:json串

  3.出参格式:json串(整体加密)

  4.使用Base64进行加密解密。具体的加密方式,可以根据需求自己进行修改。

二、过滤器

说明:接收数据时:所有的数据是加密的,请求进来后,先在过滤器中进行拦截解密,之后进行后续操作。

   响应数据时:所有的数据向客户端或者web响应时,先在过滤器中进行拦截加密,之后再响应。

   加密解密的操作在过滤器中执行。

注意:ServletRequest request, ServletResponse response 不能直接修改参数,所以采用包装类进行设置。

具体代码:import java.io.BufferedReader;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Base64; import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import com.lmbx.conf.WrapperedRequest;
import com.lmbx.conf.WrapperedResponse;
import lombok.extern.slf4j.Slf4j; @Component
@WebFilter(urlPatterns = { "/*" }, filterName = "DataFilter")
@Slf4j
public class DataFilter implements Filter { @Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub } @Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
String requestBody = getRequestBody((HttpServletRequest) request);
//解密请求报文
String requestBodyMw = new String(Base64.getDecoder().decode(requestBody), "utf-8");
log.info("解密请求数据:"+requestBodyMw);
WrapperedRequest wrapRequest = new WrapperedRequest( (HttpServletRequest) request, requestBodyMw);
WrapperedResponse wrapResponse = new WrapperedResponse((HttpServletResponse) response);
chain.doFilter(wrapRequest, wrapResponse);
byte[] data = wrapResponse.getResponseData();
log.info("原始返回数据: " + new String(data, "utf-8"));
// 加密返回报文
String responseBodyMw = Base64.getEncoder().encodeToString(data);
log.info("加密返回数据: " + responseBodyMw);
writeResponse(response, responseBodyMw);
} @Override
public void destroy() {
// TODO Auto-generated method stub } private String getRequestBody(HttpServletRequest req) {
try {
BufferedReader reader = req.getReader();
StringBuffer sb = new StringBuffer();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
String json = sb.toString();
return json;
} catch (IOException e) {
log.info("请求体读取失败"+e.getMessage());
}
return "";
} private void writeResponse(ServletResponse response, String responseString)
throws IOException {
PrintWriter out = response.getWriter();
out.print(responseString);
out.flush();
out.close();
} }

三、WrapperedRequest包装类

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
public class WrapperedRequest extends HttpServletRequestWrapper { private String requestBody = null;
HttpServletRequest req = null; public WrapperedRequest(HttpServletRequest request) {
super(request);
this.req = request;
} public WrapperedRequest(HttpServletRequest request, String requestBody) {
super(request);
this.requestBody = requestBody;
this.req = request;
} /**
* (non-Javadoc)
*
* @see javax.servlet.ServletRequestWrapper#getReader()
*/
@Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new StringReader(requestBody));
} /**
* (non-Javadoc)
*
* @see javax.servlet.ServletRequestWrapper#getInputStream()
*/
@Override
public ServletInputStream getInputStream() throws IOException {
return new ServletInputStream() {
private InputStream in = new ByteArrayInputStream(
requestBody.getBytes(req.getCharacterEncoding()));
@Override
public int read() throws IOException {
return in.read();
}
@Override
public boolean isFinished() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isReady() {
// TODO Auto-generated method stub
return false;
}
@Override
public void setReadListener(ReadListener readListener) {
// TODO Auto-generated method stub }
};
}
}
四、WrapperedResponse包装类
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
public class WrapperedResponse extends HttpServletResponseWrapper { private ByteArrayOutputStream buffer = null;
private ServletOutputStream out = null;
private PrintWriter writer = null; public WrapperedResponse(HttpServletResponse resp) throws IOException {
super(resp);
// 真正存储数据的流
buffer = new ByteArrayOutputStream();
out = new WapperedOutputStream(buffer);
writer = new PrintWriter(new OutputStreamWriter(buffer,
this.getCharacterEncoding()));
} /** 重载父类获取outputstream的方法 */
@Override
public ServletOutputStream getOutputStream() throws IOException {
return out;
} /** 重载父类获取writer的方法 */
@Override
public PrintWriter getWriter() throws UnsupportedEncodingException {
return writer;
} /** 重载父类获取flushBuffer的方法 */
@Override
public void flushBuffer() throws IOException {
if (out != null) {
out.flush();
}
if (writer != null) {
writer.flush();
}
} @Override
public void reset() {
buffer.reset();
} /** 将out、writer中的数据强制输出到WapperedResponse的buffer里面,否则取不到数据 */
public byte[] getResponseData() throws IOException {
flushBuffer();
return buffer.toByteArray();
} /** 内部类,对ServletOutputStream进行包装 */
private class WapperedOutputStream extends ServletOutputStream {
private ByteArrayOutputStream bos = null; public WapperedOutputStream(ByteArrayOutputStream stream)
throws IOException {
bos = stream;
} @Override
public void write(int b) throws IOException {
bos.write(b);
} @Override
public void write(byte[] b) throws IOException {
bos.write(b, 0, b.length);
} @Override
public boolean isReady() {
// TODO Auto-generated method stub
return false;
} @Override
public void setWriteListener(WriteListener writeListener) {
// TODO Auto-generated method stub }
}
}
五、Controller
import java.io.BufferedReader;
import java.io.InputStreamReader;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j; @RestController
@RequestMapping("/v1/api/")
@Slf4j
public class UserInfoController { //测试
@PostMapping(value = "test",produces = "application/json;charset=UTF-8")
public String test(HttpServletRequest request,HttpServletResponse response) {
JSONObject jsonObject = new JSONObject();
JSONObject clientJson = getClientJson(request, response);
log.info("【客户端收集到的数据为】clientJson={}",clientJson);
return clientJson.toString();
}
public JSONObject getClientJson(HttpServletRequest request,HttpServletResponse response) {
JSONObject json = null;
try {
//提取json
//response.setContentType("application/json; charset=utf-8");
response.setContentType("text/json");
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
BufferedReader br = null;
if (request.getContentType().contains("text") || request.getContentType().contains("json")) {
br = new BufferedReader(new InputStreamReader((ServletInputStream) request.getInputStream(), "UTF-8"));
StringBuilder sb = new StringBuilder();
String temp;
while ((temp = br.readLine()) != null) {
sb.append(temp);
}
json = JSONObject.parseObject(sb.toString());
} } catch (Exception e) {
e.printStackTrace();
log.error("客户端请求数据异常->" + e.getMessage());
}
log.info(json.toString());
return json;
} }

六、测试

说明:可以直接使用postman进行测试。

这里使用httpclient进行测试。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lmbx.util.DES;
import com.lmbx.util.DESCoderUtil; import lombok.extern.slf4j.Slf4j; @RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class test2 { @Test
public void test() throws Exception { String url="http://localhost:8080/v1/api/test";
String json="{\"placeId\":\"2\",\"mediaCode\":\"ottauto\",\"cId\":\"1\"}";
String responseBodyMw =new String(Base64.getDecoder().decode(json), "utf-8");
String doPost = doPost(url,responseBodyMw,null);
System.out.println(doPost);
} public synchronized static JSONObject doGet(String url) {
JSONObject jsonObject=null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
System.out.println(request);
HttpResponse response = client.execute(request);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String strResult = EntityUtils.toString(response.getEntity());
System.out.println("请求结果为——》"+strResult);
jsonObject=JSON.parseObject(strResult);
return jsonObject;
}
}
catch (IOException e) {
e.printStackTrace();
}
return jsonObject;
} public static String doPost(String url,String json,String token){
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
String response = null;
try {
StringEntity s = new StringEntity(json,Charset.forName("UTF-8"));
s.setContentEncoding("UTF-8");
s.setContentType("application/json");//发送json数据需要设置contentType
post.setEntity(s);
post.setHeader("token", token);
post.setHeader("Content-Type", "application/json; charset=UTF-8");
HttpResponse res = client.execute(post);
if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
HttpEntity httpEntity = res.getEntity();
BufferedReader reader = null; reader = new BufferedReader(new InputStreamReader(httpEntity.getContent(), "UTF-8"), 10 * 1024);
StringBuilder strBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
strBuilder.append(line);
}
response = strBuilder.toString();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return response;
}
}
 

   

SpringBoot框架中,使用过滤器进行加密解密操作(一)的更多相关文章

  1. CI框架中自带的加密解密如何应用

    首先我们找到配置文件application/config/config.php  ,找到如下代码: ? 1 $config['encryption_key'] = "YOUR KEY&quo ...

  2. Springboot 使用过滤器进行加密解密(二)

    之前写过一篇关于过滤器实现加密解密功能的文章,但是在实际开发业务中发现,还是有一些问题的,在此特地说明. 第一:过滤器走两遍的问题: 1.过滤器上,添加了两个注解 第一个:@Compent   将此F ...

  3. php中base64_decode与base64_encode加密解密函数

    php中base64_decode与base64_encode加密解密函数,实例分析了base64加密解密函数的具体用法,具有一定的实用价值,需要的朋友可以参考下 本文实例讲述了php中base64_ ...

  4. springboot框架中集成thymeleaf引擎,使用form表单提交数据,debug结果后台获取不到数据

    springboot框架中集成thymeleaf引擎,使用form表单提交数据,debug结果后台获取不到数据 表单html: <form class="form-horizontal ...

  5. JAVA和PYTHON同时实现AES的加密解密操作---且生成的BASE62编码一致

    终于有机会生产JAVA的东东了. 有点兴奋. 花了一天搞完.. java(关键key及算法有缩减): package com.security; import javax.crypto.Cipher; ...

  6. .NET和JAVA中BYTE的区别以及JAVA中“DES/CBC/PKCS5PADDING” 加密解密在.NET中的实现

    场景:java 作为客户端调用已有的一个.net写的server的webservice,输入string,返回字节数组. 问题:返回的值不是自己想要的,跟.net客户端直接调用总是有差距 分析:平台不 ...

  7. C#中的三种 加密解密

    刚刚学会的C#的加密与解密(三种)MD5加密/RSA加密与解密/DES加密.也是刚刚申请的blog随便发布一下. (一).MD5加密 MD5 md5 = new MD5CryptoServicePro ...

  8. Springboot框架中request.getInputStream()获取不到上传的文件流

    Springboot框架中用下面的代码,使用request.getInputStream()获取不到上传的文件流 @PostMapping("/upload_img") publi ...

  9. SpringBoot项目中,表单的验证操作

    在创建Springboot项目中,我们使用了表单验证操作,这一操作将极大地简化我们编程的开发 1.接收数据,以及验证 @PostMapping("/save") public Mo ...

随机推荐

  1. js 表格操作(兼容模式

    用insertRow,insertRow操作表格时,发现在谷歌浏览器中顺序和IE是反的 // 表格新增行 function addTableRow($id,$arr,$rowAttr){ var ta ...

  2. [Oracle][RMAN]关于Oracle RMAN里面的Merged Incremental Backups的Tag分离机能

    关于Oracle RMAN里面的Merged Incremental Backups的机能,RMAN使用的比较多的DBA们可能会有所了解. 基本上,每次都实行同样的Backup命令即可完成BACK. ...

  3. 机器学习 xgboost 笔记

    一.数据预处理.特征工程 类别变量 labelencoder就够了,使用onehotencoder反而会降低性能.其他处理方式还有均值编码(对于存在大量分类的特征,通过监督学习,生成数值变量).转换处 ...

  4. lintcode 程序题

    1500802025 才仁代吉 第一链表类参数是整形链表,广度优先遍历: 队列是先进先出的概念 所以使用于保存节点 2插树的话 1个节点有个2个子节点 先将根节点入队,然后访问根节点数据(此时让根节点 ...

  5. apk的api级别不要低于26

    谷歌要求 api级别 最低26, 在用 xbuliber打包app的时候,可以在 manifest.json增加下面的代码. "plus": { "distribute& ...

  6. LVM逻辑卷扩容、缩容

    LVM就是动态卷管理,可以将多个硬盘和硬盘分区做成一个逻辑卷,并把这个逻辑卷作为一个整体来统一管理,动态对分区进行扩缩空间大小,安全快捷方便管理. 后期出现问题恢复数据也比较麻烦. 概念: ①PE(P ...

  7. jenkins问题整理

    --------------------------------这是一个模板------------------------------------- 问题1:jenkins服务器上传jar包到指定服 ...

  8. [Kafka] [All about it]

    Overview 设计目标: 以O(1) 常数级时间复杂度的访问性能,提供消息持久化能力. 高吞吐率. 支持 kafka server 间的消息分区,及分布式消费,同时保证每个partition内部的 ...

  9. Linux:OpenSUSE系统的安装

    又过了比较长的时间,基本上都是一周一更了,这期我们就来演示Linux系统中OpenSUSE系统的安装吧! 安装OpenSUSE系统 系统映像文件下载 OpenSUSE 15下载地址: https:// ...

  10. soapui 测试 带hear 验证的写法

    <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web=& ...