springboot接口加解密传输
前言:
写这个博客的目的也是想着后面如果需要用上的时候方便参考,这篇文章使用的也是比较简单的加解密流程,但这篇文章注重点是后端对于前端传过来的加密参数怎么接收,然后统一拦截解密后又回到原本接口上, 接口返回结果时又是怎么将结果集加密后传输出去
还有一个很重要的点是接口一般是有post和get两种请求方式,对于这两种方式的拦截这一块是有讲究的, 很多博客大多讲的是单一方式,导致测试时接口出现未知错误时一脸茫然
参考博客地址
SpringBoot+Vue 后端输出加密,前端请求统一解密
Springboot实现接口传输加解密
一. 后端解析前端传过来的参数
des加解密工具类
public class DESUtil { private static String strDefaultKey = "admin"; private Cipher encryptCipher = null; private Cipher decryptCipher = null; public static String byteArr2HexStr(byte[] arrB) throws Exception { int iLen = arrB.length; StringBuffer sb = new StringBuffer(iLen * 2); for (int i = 0; i < iLen; i++) { int intTmp = arrB[i]; while (intTmp < 0) { intTmp = intTmp + 256; } if (intTmp < 16) { sb.append("0"); } sb.append(Integer.toString(intTmp, 16)); } return sb.toString(); } public static byte[] hexStr2ByteArr(String strIn) throws Exception { byte[] arrB = strIn.getBytes(); int iLen = arrB.length; byte[] arrOut = new byte[iLen / 2]; for (int i = 0; i < iLen; i = i + 2) { String strTmp = new String(arrB, i, 2); arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16); } return arrOut; } public DESUtil() throws Exception { this(strDefaultKey); } public DESUtil(String strKey) throws Exception { if (strKey == null) return; java.security.Security.addProvider(new com.sun.crypto.provider.SunJCE()); Key key = getKey(strKey.getBytes()); encryptCipher = Cipher.getInstance("DES"); encryptCipher.init(Cipher.ENCRYPT_MODE, key); decryptCipher = Cipher.getInstance("DES"); decryptCipher.init(Cipher.DECRYPT_MODE, key); } public void renderKey(String strKey) throws Exception { if (strKey == null) return; java.security.Security.addProvider(new com.sun.crypto.provider.SunJCE()); Key key = getKey(strKey.getBytes()); encryptCipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); encryptCipher.init(Cipher.ENCRYPT_MODE, key); decryptCipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); decryptCipher.init(Cipher.DECRYPT_MODE, key); } public byte[] encrypt(byte[] arrB) throws Exception { return encryptCipher.doFinal(arrB); } public String encrypt(String strIn) throws Exception { return byteArr2HexStr(encrypt(strIn.getBytes())); } public byte[] decrypt(byte[] arrB) throws Exception { return decryptCipher.doFinal(arrB); } public String decrypt(String strIn) throws Exception { return new String(decrypt(hexStr2ByteArr(strIn))); } private Key getKey(byte[] arrBTmp) throws Exception { byte[] arrB = new byte[8]; for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) { arrB[i] = arrBTmp[i]; } Key key = new javax.crypto.spec.SecretKeySpec(arrB, "DES"); return key; } /** * 加密 * * @param key 密钥 * @param str 需要加密的字符串 * @return */ public static String encode(String key, String str) { DESUtil des = null; try { des = new DESUtil(key); return des.encrypt(str); } catch (Exception ex) { } return ""; } public static String decode(String key, String str) { DESUtil des = null; try { des = new DESUtil(key); return des.decrypt(str); } catch (Exception ex) { System.out.println(ex.getMessage()); } return ""; } public static String decode(String key, String str,String charset) { DESUtil des = null; try { des = new DESUtil(key); return des.decrypt(str,charset); } catch (Exception ex) { } return ""; } public String decrypt(String strIn,String charset) throws Exception { return new String(decrypt(hexStr2ByteArr(strIn)),charset); } }
这里是用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);
}
//读取body参数(这个类下面有)
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");
//这一步将加密的json按照特定规则解密(前后端统一加密的key为admin)
String resultParam = DESUtil.decode("admin",json.toString());
System.out.println(resultParam);
Class<?> c = args[0].getClass();
//将获取解密后的真实参数,封装到接口入参的类中
Object o = JSONObject.parseObject(resultParam, 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; } }
三.接口测试
先从get请求开始吧
这是我没加注解之前的样子,并且把加密串输出一下
// @JmAspect @GetMapping("/bkTaskInfo") @ApiOperation(value = "bkTaskInfo",notes = "布控任务详情") public BkTaskDto bkTaskInfo(@RequestParam("id") String id, @RequestParam("name")String name) { log.info("bkTaskInfo_布控任务详情 params:{}", id); System.out.println(DESUtil.encode("admin",id)); System.out.println(DESUtil.encode("admin",name)); return bkTaskService.bkTaskInfo(id); }
执行之后拿加密后的json串赋值到对应字段上(并把切面注解放开)
执行接口通过debug调式参数均被正常解析接口正常运行
post其实也差不多,主要给大家看一下前后交互的参数传递方式
类似这种用json格式传递参数,参数也为json,也可以自定义但后端代码解析时参数也需改下
但有一点需要注意下,我这边post请求参数都是放到一个实体类里面,所以如果你不是这种的话不确定会不会造成差异
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!