前言:
写这个博客的目的也是想着后面如果需要用上的时候方便参考,这篇文章使用的也是比较简单的加解密流程,但这篇文章注重点是后端对于前端传过来的加密参数怎么接收,然后统一拦截解密后又回到原本接口上, 接口返回结果时又是怎么将结果集加密后传输出去
还有一个很重要的点是接口一般是有post和get两种请求方式,对于这两种方式的拦截这一块是有讲究的, 很多博客大多讲的是单一方式,导致测试时接口出现未知错误时一脸茫然
参考博客地址
SpringBoot+Vue 后端输出加密,前端请求统一解密
https://blog.csdn.net/qq_38387996/article/details/128938753
Springboot实现接口传输加解密
https://blog.csdn.net/qq243920161/article/details/131261863
一. 后端解析前端传过来的参数
这里是用aop切面+注解的方式拦截前端请求并分别获取get和post参数进行解密后让接口跟正常接口一样执行
注解类
/** * @author admin * @date 2024/1/22 * 使用了该注解的接口会走aop **/ @Target({ElementType.METHOD, ElementType.FIELD, ElementType.TYPE, }) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface JmAspect { String code() default ""; }
aop拦截类
@Aspect
@Order(1)
@Component
public class DESGetDeleteDecryptAspect {
// 切入点:只有使用了@JmAspect注解的请求才会执行解密
@Pointcut("@annotation(com.chinaoly.utils.config.aes.JmAspect)")
public void pointcut() { }
@Around("pointcut()")
public Object aroundMethod(ProceedingJoinPoint joinPoint) throws Throwable {
// 获取request加密传递的参数
HttpServletRequest request = getRequest();
// 获取到请求的参数列表进行解密
Object[] args = joinPoint.getArgs();
Object[] newArgs = args;
//post请求
if (Objects.equals("POST", request.getMethod())) {
RequestWrapper requestBodyWrapper;
//用request读取post传过来的body数据
if (request instanceof RequestWrapper) {
requestBodyWrapper = (RequestWrapper) request;
} else {
requestBodyWrapper = new RequestWrapper(request);
}
String body = requestBodyWrapper.getBody();
JSONObject jsonObject = JSONObject.parseObject(body);
Map<String, Object> map = (Map<String, Object>)jsonObject;
//这个json是前端将请求参数统一加密后变成的json串 传输字符串为 {json: 加密串}
Object json = map.get("json");
String json3 = DESUtil.decode("admin",json.toString());
System.out.println(json3);
Class<?> c = args[0].getClass();
//将获取解密后的真实参数,封装到接口入参的类中
Object o = JSONObject.parseObject(json3, c);
newArgs = new Object[]{o};
} else if (Objects.equals("GET", request.getMethod())) {
//get请求参数解析
this.decrypt(newArgs);
}
// 执行将解密的结果交给控制器进行处理,并返回处理结果
return joinPoint.proceed(newArgs);
}
/**
* 获取request
*/
private HttpServletRequest getRequest() {
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = requestAttributes.getRequest();
return request;
}
// 解密方法
@SuppressWarnings("unchecked")
public void decrypt(Object[] args) throws DESException {
//将请求参数数组进行遍历解密(多个参数)
for (int i = 0; i < args.length; i++) {
String encrypt = args[i].toString();
// 将密文解密为JSON字符串
String json = DESUtil.decode("admin",encrypt);
//将解密后的内容赋予参数数组
args[i] = json;
}
//单参数解密
// String encrypt =args[0].toString();
// // 将密文解密为JSON字符串
// String json = DESUtil.decode("admin",encrypt);
// Object[] arr = new Object[1];
// arr[0] = json;
// System.out.println(arr);
// // 将JSON字符串转换为Map集合,并替换原本的参数
// args[0] = json;
}
}
DESException(异常类不是很重要)
public class DESException extends Exception { public DESException(String msg) { super(msg); } }
RequestWrapper(读取body参数)
public class RequestWrapper extends HttpServletRequestWrapper { private final String body; public RequestWrapper(HttpServletRequest request) { super(request); StringBuilder stringBuilder = new StringBuilder(); BufferedReader bufferedReader = null; InputStream inputStream = null; try { inputStream = request.getInputStream(); 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) { } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (bufferedReader != null) { try { bufferedReader.close(); } catch (IOException e) { e.printStackTrace(); } } } body = stringBuilder.toString(); } @Override public ServletInputStream getInputStream() throws IOException { final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes()); ServletInputStream servletInputStream = new ServletInputStream() { @Override public boolean isFinished() { return false; } @Override public boolean isReady() { return false; } @Override public void setReadListener(ReadListener readListener) { } @Override public int read() throws IOException { return byteArrayInputStream.read(); } }; return servletInputStream; } @Override public BufferedReader getReader() throws IOException { return new BufferedReader(new InputStreamReader(this.getInputStream())); } public String getBody() { return this.body; } }
二.后端对结果进行加密
响应加解密拦截器
@Aspect @Component @ControllerAdvice public class ResponseHandler implements ResponseBodyAdvice<Object> { /** * 返回true,才会走beforeBodyWrite方法 */ @Override public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
//这里特意加上了JmAspect,意味着只有加了该注解的方法才会走beforeBodyWrite方法 return methodParameter.hasMethodAnnotation(JmAspect.class); // return true; } /** * 响应加密 */ @Override public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest request, ServerHttpResponse serverHttpResponse) { // 拿到响应的数据 String json = JSON.toJSONString(body); // 进行加密 String result = DESUtil.encode("admin",json); System.out.println(result); return result; } }
剩下的就是根据接口进行测试了
标签:return,springboot,加解密,Object,request,接口,json,public,String From: https://www.cnblogs.com/magepi/p/18001570