AES实现后端参数加解密

  • 前言
  • 介绍
  • Start
    • 引入依赖
    • 编写AES加解密工具类
    • 自定义注解
    • 编写请求数据解密 ControllerAdvice
    • 编写返回数据加密 ControllerAdvice
    • 测试
  • 图表
    • 时序图
    • 流程图

前言

在实际工作中为了安全,会将参数进行密文传输,这里使用的是 AES + ECB + BASE64 对称加密的加密方式,在此记录并学习一下,技术不精望大家谅解。

介绍

AES加密是一种对称加密,有对称加密自然也有非对称加密

对称加密
对称加密是一种简单快速的加密方式,它在加密和解密的时候使用的密钥是同一个,并且通常不会超过256bit,密钥越小,在加解密的时候耗时越短,但是同样的,对于数据的加密会稍弱一些。本文使用的加密方式正是对称加密

非对称加密
非对称加密提供了一种更为安全的加解密解决方案,它使用了一对密钥,也就是一个公钥和一个私钥。在加密的时候使用公钥加密,且公钥可以发给任何请求的人,而解密的时候则需要使用私钥去解密。但是相应的,加解密的速度会稍慢。

总结来说:
对称加密的速度更快,但密钥传输相对麻烦,且加密稍弱,有泄露风险;
非对称加密的安全性更高,加密方式较强,密钥传输简单,但加密速度较慢,几乎没有泄露风险,适合偶尔传输数据的请求。

Start

引入依赖

使用之前要先引入此依赖

     <dependency><groupId>org.apache.directory.studio</groupId><artifactId>org.apache.commons.codec</artifactId><version>1.8</version></dependency>

编写AES加解密工具类

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.util.JSONPObject;
import org.apache.commons.codec.binary.Base64;import java.util.HashMap;
import java.util.Map;public class AesEncryptUtils {//密钥 16位 可自定义//注意:此处的密钥要与前端一致,否则会导致解密失败private static final String KEY = "Mh82Pw93Q0ePaz5";//算法名称/加密模式/数据填充方式//注意: 加密方式与数据填充方式要与前端对应,否则会加密失败//这里使用的是ECB加密方式,数据填充使用的是PKCS5private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";/*** 加密* @param content 加密的字符串* @param encryptKey key值* @return* @throws Exception*/public static String encrypt(String content, String encryptKey) throws Exception {KeyGenerator kgen = KeyGenerator.getInstance("AES");kgen.init(128);Cipher cipher = Cipher.getInstance(ALGORITHMSTR);cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), "AES"));byte[] b = cipher.doFinal(content.getBytes("utf-8"));// 采用base64算法进行转码,避免出现中文乱码return Base64.encodeBase64String(b);}/*** 解密* @param encryptStr 解密的字符串* @param decryptKey 解密的key值* @return* @throws Exception*/public static String decrypt(String encryptStr, String decryptKey) throws Exception {KeyGenerator kgen = KeyGenerator.getInstance("AES");kgen.init(128);// 根据算法名称/加密方式/填充方式初始化加密Cipher cipher = Cipher.getInstance(ALGORITHMSTR);cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"));// 采用base64算法进行转码,避免出现中文乱码byte[] encryptBytes = Base64.decodeBase64(encryptStr);byte[] decryptBytes = cipher.doFinal(encryptBytes);return new String(decryptBytes);}public static String encrypt(String content) throws Exception {return encrypt(content, KEY);}public static String decrypt(String encryptStr) throws Exception {return decrypt(encryptStr, KEY);}
}

以上则是AES用来加解密的工具类,可写个单元测试或写个main方法来测试是否可以正常加解密成功。

自定义注解

该注解可用于方法上,对需要加密的接口进行粒子化控制

import org.springframework.web.bind.annotation.Mapping;
import java.lang.annotation.*;/*** 出入参加解密*/
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Mapping
@Documented
public @interface AES {/*** 入参是否解密,默认解密*/boolean inDecode() default true;/*** 出参是否加密,默认加密*/boolean outEncode() default true;
}

编写请求数据解密 ControllerAdvice

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;/*** 请求数据解密*/
@ControllerAdvice(basePackages = "com.xxx.controller")
public class DecodeRequestBodyAdvice implements RequestBodyAdvice {private static final Logger logger = LoggerFactory.getLogger(DecodeRequestBodyAdvice.class);@Overridepublic boolean supports(MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {return true;}@Overridepublic Object handleEmptyBody(Object body, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {return body;}@Overridepublic HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) throws IOException {try {boolean encode = false;if (methodParameter.getMethod().isAnnotationPresent(SecurityParameter.class)) {//获取注解配置的包含和去除字段SecurityParameter serializedField = methodParameter.getMethodAnnotation(SecurityParameter.class);//入参是否需要解密encode = serializedField.inDecode();}if (encode) {logger.info("对方法method :【" + methodParameter.getMethod().getName() + "】返回数据进行解密");return new MyHttpInputMessage(inputMessage);} else {return inputMessage;}} catch (Exception e) {e.printStackTrace();logger.error("对方法method :【" + methodParameter.getMethod().getName() + "】返回数据进行解密出现异常:" + e.getMessage());return inputMessage;}}@Overridepublic Object afterBodyRead(Object body, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {return body;}class MyHttpInputMessage implements HttpInputMessage {private HttpHeaders headers;private InputStream body;public MyHttpInputMessage(HttpInputMessage inputMessage) throws Exception {this.headers = inputMessage.getHeaders();String requestData = IOUtils.toString(inputMessage.getBody(), "UTF-8");//去除请求数据中的转义字符String encryptStr = easpString(requestData).replace("\"", "");String decrypt = AesEncryptUtils.decrypt(encryptStr);this.body = IOUtils.toInputStream(decrypt, "UTF-8");}@Overridepublic InputStream getBody() throws IOException {return body;}@Overridepublic HttpHeaders getHeaders() {return headers;}/*** @param requestData* @return*/public String easpString(String requestData) {if (requestData != null && !requestData.equals("")) {String s = "{\"requestData\":";//去除requestData中的转义字符String data = requestData.replaceAll("\\s*|\r|\n|\t", "");if (!data.startsWith(s)) {throw new RuntimeException("参数【requestData】缺失异常!");} else {int closeLen = data.length() - 1;int openLen = "{\"requestData\":".length();String substring = StringUtils.substring(data, openLen, closeLen);return substring;}}return "";}}
}

编写返回数据加密 ControllerAdvice

import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;/*** 返回数据加密*/
@ControllerAdvice(basePackages = "com.xxx.controller")
public class EncodeResponseBodyAdvice implements ResponseBodyAdvice {private final static Logger logger = LoggerFactory.getLogger(EncodeResponseBodyAdvice.class);@Overridepublic boolean supports(MethodParameter methodParameter, Class aClass) {return true;}@Overridepublic Object beforeBodyWrite(Object body,MethodParameter methodParameter,MediaType mediaType,Class aClass,ServerHttpRequest serverHttpRequest,ServerHttpResponse serverHttpResponse) {boolean encode = false;if (methodParameter.getMethod().isAnnotationPresent(SecurityParameter.class)) {//获取注解配置的包含和去除字段SecurityParameter serializedField = methodParameter.getMethodAnnotation(SecurityParameter.class);//出参是否需要加密encode = serializedField.outEncode();}if (encode) {logger.info("对方法method :【" + methodParameter.getMethod().getName() + "】返回数据进行加密");ObjectMapper objectMapper = new ObjectMapper();try {String result = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(body);return AesEncryptUtils.encrypt(result);} catch (Exception e) {e.printStackTrace();logger.error("对方法method :【" + methodParameter.getMethod().getName() + "】返回数据进行解密出现异常:" + e.getMessage());}}return body;}
}

测试

此时我们已经编写完所有代码,我们来写一个测试类来测试加解密是否正常


我们写了两个接口,getSecret是获取返回内容的密文,getBySecret是解析密文
此时我们使用postman来测试一下接口

getSecret


可以看到我们可以正常获取到密文,那我们使用这个密文来调用另外一个接口看是否能正确解析出密文内容

getBySecret


可以看到密文已经被成功解析出来了,同时也是我们加密前的内容。
自此我们的加解密就全部结束啦,如果想要出参加密、入参解密的话直接加上注解,不带属性即可

注意:此处后端使用的是加密名为AES,加密方式为ECB,数据填充格式为PKCS5Padding。前后端一定要完全一致,否则会导致前后端解密失败

图表

为了便于大家理解,在这里做了两个图表参考

时序图

#mermaid-svg-F5VfBzrHHSi1ce8W {font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}#mermaid-svg-F5VfBzrHHSi1ce8W .error-icon{fill:#552222;}#mermaid-svg-F5VfBzrHHSi1ce8W .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-F5VfBzrHHSi1ce8W .edge-thickness-normal{stroke-width:2px;}#mermaid-svg-F5VfBzrHHSi1ce8W .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-F5VfBzrHHSi1ce8W .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-F5VfBzrHHSi1ce8W .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-F5VfBzrHHSi1ce8W .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-F5VfBzrHHSi1ce8W .marker{fill:#333333;stroke:#333333;}#mermaid-svg-F5VfBzrHHSi1ce8W .marker.cross{stroke:#333333;}#mermaid-svg-F5VfBzrHHSi1ce8W svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-F5VfBzrHHSi1ce8W .actor{stroke:hsl(259.6261682243, 59.7765363128%, 87.9019607843%);fill:#ECECFF;}#mermaid-svg-F5VfBzrHHSi1ce8W text.actor>tspan{fill:black;stroke:none;}#mermaid-svg-F5VfBzrHHSi1ce8W .actor-line{stroke:grey;}#mermaid-svg-F5VfBzrHHSi1ce8W .messageLine0{stroke-width:1.5;stroke-dasharray:none;stroke:#333;}#mermaid-svg-F5VfBzrHHSi1ce8W .messageLine1{stroke-width:1.5;stroke-dasharray:2,2;stroke:#333;}#mermaid-svg-F5VfBzrHHSi1ce8W #arrowhead path{fill:#333;stroke:#333;}#mermaid-svg-F5VfBzrHHSi1ce8W .sequenceNumber{fill:white;}#mermaid-svg-F5VfBzrHHSi1ce8W #sequencenumber{fill:#333;}#mermaid-svg-F5VfBzrHHSi1ce8W #crosshead path{fill:#333;stroke:#333;}#mermaid-svg-F5VfBzrHHSi1ce8W .messageText{fill:#333;stroke:#333;}#mermaid-svg-F5VfBzrHHSi1ce8W .labelBox{stroke:hsl(259.6261682243, 59.7765363128%, 87.9019607843%);fill:#ECECFF;}#mermaid-svg-F5VfBzrHHSi1ce8W .labelText,#mermaid-svg-F5VfBzrHHSi1ce8W .labelText>tspan{fill:black;stroke:none;}#mermaid-svg-F5VfBzrHHSi1ce8W .loopText,#mermaid-svg-F5VfBzrHHSi1ce8W .loopText>tspan{fill:black;stroke:none;}#mermaid-svg-F5VfBzrHHSi1ce8W .loopLine{stroke-width:2px;stroke-dasharray:2,2;stroke:hsl(259.6261682243, 59.7765363128%, 87.9019607843%);fill:hsl(259.6261682243, 59.7765363128%, 87.9019607843%);}#mermaid-svg-F5VfBzrHHSi1ce8W .note{stroke:#aaaa33;fill:#fff5ad;}#mermaid-svg-F5VfBzrHHSi1ce8W .noteText,#mermaid-svg-F5VfBzrHHSi1ce8W .noteText>tspan{fill:black;stroke:none;}#mermaid-svg-F5VfBzrHHSi1ce8W .activation0{fill:#f4f4f4;stroke:#666;}#mermaid-svg-F5VfBzrHHSi1ce8W .activation1{fill:#f4f4f4;stroke:#666;}#mermaid-svg-F5VfBzrHHSi1ce8W .activation2{fill:#f4f4f4;stroke:#666;}#mermaid-svg-F5VfBzrHHSi1ce8W .actorPopupMenu{position:absolute;}#mermaid-svg-F5VfBzrHHSi1ce8W .actorPopupMenuPanel{position:absolute;fill:#ECECFF;box-shadow:0px 8px 16px 0px rgba(0,0,0,0.2);filter:drop-shadow(3px 5px 2px rgb(0 0 0 / 0.4));}#mermaid-svg-F5VfBzrHHSi1ce8W .actor-man line{stroke:hsl(259.6261682243, 59.7765363128%, 87.9019607843%);fill:#ECECFF;}#mermaid-svg-F5VfBzrHHSi1ce8W .actor-man circle,#mermaid-svg-F5VfBzrHHSi1ce8W line{stroke:hsl(259.6261682243, 59.7765363128%, 87.9019607843%);fill:#ECECFF;stroke-width:2px;}#mermaid-svg-F5VfBzrHHSi1ce8W :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} 前端 后端 DecodeRequestBodyAdvice 业务处理 EncodeResponseBodyAdvice 发送加密数据 解密 解密后的参数 加密返回信息 返回加密信息 前端 后端 DecodeRequestBodyAdvice 业务处理 EncodeResponseBodyAdvice

流程图

#mermaid-svg-5JSKIBLQ0LzOr16q {font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}#mermaid-svg-5JSKIBLQ0LzOr16q .error-icon{fill:#552222;}#mermaid-svg-5JSKIBLQ0LzOr16q .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-5JSKIBLQ0LzOr16q .edge-thickness-normal{stroke-width:2px;}#mermaid-svg-5JSKIBLQ0LzOr16q .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-5JSKIBLQ0LzOr16q .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-5JSKIBLQ0LzOr16q .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-5JSKIBLQ0LzOr16q .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-5JSKIBLQ0LzOr16q .marker{fill:#333333;stroke:#333333;}#mermaid-svg-5JSKIBLQ0LzOr16q .marker.cross{stroke:#333333;}#mermaid-svg-5JSKIBLQ0LzOr16q svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-5JSKIBLQ0LzOr16q .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-5JSKIBLQ0LzOr16q .cluster-label text{fill:#333;}#mermaid-svg-5JSKIBLQ0LzOr16q .cluster-label span{color:#333;}#mermaid-svg-5JSKIBLQ0LzOr16q .label text,#mermaid-svg-5JSKIBLQ0LzOr16q span{fill:#333;color:#333;}#mermaid-svg-5JSKIBLQ0LzOr16q .node rect,#mermaid-svg-5JSKIBLQ0LzOr16q .node circle,#mermaid-svg-5JSKIBLQ0LzOr16q .node ellipse,#mermaid-svg-5JSKIBLQ0LzOr16q .node polygon,#mermaid-svg-5JSKIBLQ0LzOr16q .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-5JSKIBLQ0LzOr16q .node .label{text-align:center;}#mermaid-svg-5JSKIBLQ0LzOr16q .node.clickable{cursor:pointer;}#mermaid-svg-5JSKIBLQ0LzOr16q .arrowheadPath{fill:#333333;}#mermaid-svg-5JSKIBLQ0LzOr16q .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-5JSKIBLQ0LzOr16q .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-5JSKIBLQ0LzOr16q .edgeLabel{background-color:#e8e8e8;text-align:center;}#mermaid-svg-5JSKIBLQ0LzOr16q .edgeLabel rect{opacity:0.5;background-color:#e8e8e8;fill:#e8e8e8;}#mermaid-svg-5JSKIBLQ0LzOr16q .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-5JSKIBLQ0LzOr16q .cluster text{fill:#333;}#mermaid-svg-5JSKIBLQ0LzOr16q .cluster span{color:#333;}#mermaid-svg-5JSKIBLQ0LzOr16q div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-5JSKIBLQ0LzOr16q :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;}

发送加密信息
解密
加密
前端
后端
是否开启解密
DecodeRequestBodyAdvice
业务处理
是否开启加密
EncodeResponseBodyAdvice

AES实现后端参数加解密相关推荐

  1. 学习加密(四)spring boot 使用RSA+AES混合加密,前后端传递参数加解密

    学习加密(四)spring boot 使用RSA+AES混合加密,前后端传递参数加解密 技术标签: RSA  AES  RSA AES  混合加密  整合 前言:    为了提高安全性采用了RSA,但 ...

  2. angular和JAVA实现aes、rsa加密解密,前后端交互,前端加解密和后端JAVA加解密实现

    今天实现了下AES和RSA加密解密,主要的功能是对前后端交互数据进行加密解密,为什么要用到两个算法呢,首先RSA默认的话加密长度是有限的100多个byte吧大约,并且需要公钥私钥,而AES加密没有限制 ...

  3. 三分钟撸完前后端crypto-js加解密,你学废了吗?

    文章目录 前言 一.AES概念 二.前端加密 1.安装依赖库 2.实现AES加密算法 3.前端演示效果 三.后端加密 1.加密工具类 2.加密测试 四.Security实现密码加解密 1.前台加密 1 ...

  4. 前后端数据加解密的几种方式比较

    对称加密 对称加密指的就是加密和解密使用同一个秘钥,所以叫做对称加密.对称加密只有一个秘钥,作为私钥. 具体算法有:DES,3DES,TDEA,Blowfish,RC5,IDEA.常见的有:DES,A ...

  5. 接口参数加解密,代码无侵入这样做方便多了

    为啥接口加解密 在我们做接口的时候,如果是外部用户直接能看到我们的参数,可能会造成我们的接口不安全,比如直接用明文的参数请求我们的接口,把参数自己定义,脏数据就会存到我们的数据库中,严重的话导致我们的 ...

  6. java 请求参数加解密

    项目开发中,需要针对请求参数加密 解密操作 可以使用下列工具类 oap.security.enabled=true oap.security.enableIgnoreAnnotation=true o ...

  7. Spring Boot 使用AES前后端传递参数加解密

    1.创建工具类 import lombok.extern.slf4j.Slf4j; import org.apache.commons.codec.binary.Base64;import javax ...

  8. 学习加密(四)spring boot 使用RSA+AES混合加密,前后端传递参数加解密(方式一)

    参考地址:https://blog.csdn.net/baidu_38990811/article/details/83540404

  9. AES的CFB模式加解密不一致的原因

    问题: 如上图,AES的CFB加密方式不仅加密和解密不能使用同一个对象,就连加密的时候同一个对象都不能使用两次,否则就会如下图: 即使明文(data),密钥(key),偏移量(iv),填充(paddi ...

最新文章

  1. 5条出人意外的大脑秘密,奇奇怪怪的知识又增加了!
  2. Java面向对象(一)面向对象简介和初步 了解
  3. 通过postman向OpenTSDB插入数据并查询
  4. 全球每天产生100篇机器学习新论文!谷歌大脑负责人Jeff Dean发推引热议,网友:太浪费时间...
  5. zabbix4.0LTS安装配置
  6. 计算机专业选电科还是华科,西交、华科与两电一邮:5所高校怎么选?工科选西交,学IT选北邮...
  7. Nginx源码分析 - 基础数据结构篇 - 单向链表结构 ngx_list.c(06)
  8. ICPC North Central NA Contest 2017 B - Pokemon Go Go
  9. 【Prison Break】第二天(3.28)
  10. docker 部署Java项目
  11. BIG5编码, GB编码(GB2312, GBK, ...), Unicode编码, UTF8, WideChar, MultiByte, Char 说明与区别
  12. 圣经与超级计算机,圣经创世纪里的时间概念和爱因斯坦相对论
  13. ASM文件类型和模板
  14. 《计算机网络教程》(微课版 第五版) 第六章 网络应用层 课后习题及答案
  15. 努比亚计科学计算机,努比亚Z系列迎来迭代新机,Geekbench跑分出炉,预计春节后发布...
  16. 小红书关键词搜索商品列表API接口(分类ID搜索商品数据接口,商品详情接口)
  17. [NOIP2008] 立体图-解题报告
  18. 文件的后缀名怎样重命名,重命名为大写字母
  19. 在服务器系统Windows 2003安装Avira AntiVir小红伞免费个人版
  20. 2020 最好的Linux网络监控工具(翻译)

热门文章

  1. linux下打印机监控,Linux下控制打印机笔记
  2. java做机器视觉_机器视觉用什么语言开发_机器视觉用什么硬件
  3. c语言菜单即功能,C语言 菜单专题
  4. 2021-2027全球与中国单点润滑器市场现状及未来发展趋势
  5. Win11任务栏消息提醒功能如何开启教学
  6. asp.net909-大型社区包裹代收与分发系统
  7. 【neutron】Neutron的基本原理与代码实现
  8. html如何制作悬浮窗,使用js实现悬浮窗效果方法
  9. Android 悬浮窗基本使用
  10. 微信小程序----事件绑定