需要的依赖
<!-- aop切面 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
<version>2.6.13</version>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
<version>1.16.4</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>28.1-jre</version>
</dependency>
自定义注解
package com.czc.datamask.annotation;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import java.lang.annotation.*;
/**
* 数据加密注解 ——与方法加密注解配合使用
*/
@Documented
@Target(ElementType.FIELD) //注解生效在字段上
@Retention(RetentionPolicy.RUNTIME)//在运行时生效
@Order(Ordered.HIGHEST_PRECEDENCE)//设置优先级
public @interface Dataprocess {
}
package com.czc.datamask.annotation;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import java.lang.annotation.*;
/**
* 方法加密注解 ——与数据加密注解配合使用
*/
@Documented
@Target(ElementType.METHOD) //注解生效在方法上
@Retention(RetentionPolicy.RUNTIME)//在运行时生效
@Order(Ordered.HIGHEST_PRECEDENCE)//设置优先级
public @interface MethodProcess {
}
加密工具类(使用的ase对称加密)
package com.czc.datamask.util;
import org.springframework.util.Base64Utils;
import org.springframework.util.StringUtils;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
/**
* ASE加密工具类
*/
public class AseUtil {
private static final String KEY_ALGORITHM = "AES";
private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";//默认的加密算法
/**
* AES 加密操作
*
* @param content 待加密内容
* @param password 加密密码
* @return 返回Base64转码后的加密数据
*/
public static String encrypt(String content, String password) {
try {
if (!StringUtils.isEmpty(content)) {
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);// 创建密码器
byte[] byteContent = content.getBytes("utf-8");
cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(password));// 初始化为加密模式的密码器
byte[] result = cipher.doFinal(byteContent);// 加密
return Base64Utils.encodeToString(result);
}
return null;
} catch (Exception ex) {
Logger.getLogger(AseUtil.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
/**
* AES 解密操作
*
* @param content
* @param password
* @return
*/
public static String decrypt(String content, String password) {
try {
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, getSecretKey(password));
byte[] result = cipher.doFinal(Base64Utils.decodeFromString(content));
return new String(result, "utf-8");
} catch (InvalidKeyException e) {
Logger.getLogger(AseUtil.class.getName()).log(Level.SEVERE, "解密失败,可能是由于加密的盐不同", e);
} catch (Exception ex) {
return content;
}
return content;
}
/**
* 生成加密秘钥
*
* @return
*/
private static SecretKeySpec getSecretKey(final String password) {
//返回生成指定算法密钥生成器的 KeyGenerator 对象
KeyGenerator kg = null;
try {
kg = KeyGenerator.getInstance(KEY_ALGORITHM);
//AES 要求密钥长度为 128
kg.init(128, new SecureRandom(password.getBytes()));
//生成一个密钥
SecretKey secretKey = kg.generateKey();
return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);// 转换为AES专用密钥
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(AseUtil.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
}
配置文件中增加配置
aop切面类
package com.czc.datamask.aop;
import com.czc.datamask.annotation.Dataprocess;
import com.czc.datamask.util.AseUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Objects;
@Order(Ordered.HIGHEST_PRECEDENCE)
@Component
@Aspect
public class DataProcessAspect {
Logger log = LoggerFactory.getLogger(this.getClass());
@Value("${secretKey}")
private String secretKey;
@Pointcut("@annotation(com.czc.datamask.annotation.MethodProcess)")
public void annotationPointCut() {
}
@Around("annotationPointCut()")
public Object around(ProceedingJoinPoint joinPoint) {
Object responseObj = null;
try {
if (joinPoint.getArgs().length != 0) { //请求参数不为空的情况下
Object requestObj = joinPoint.getArgs()[0];
handleEncrypt(requestObj);
}
responseObj = joinPoint.proceed();
handleDecrypt(responseObj);
} catch (NoSuchMethodException e) {
e.printStackTrace();
log.error("Aop自动加解密处理出现异常{}", e);
} catch (Throwable throwable) {
throwable.printStackTrace();
log.error("Aop自动加解密处理出现异常{}", throwable);
}
return responseObj;
}
/**
* 处理加密
*
* @param requestObj
*/
private void handleEncrypt(Object requestObj) throws IllegalAccessException {
if (Objects.isNull(requestObj)) {
return;
}
if (requestObj instanceof List) {
List<Object> requestList = (List<Object>) requestObj;
for (Object obj : requestList) {
encryptFields(obj);
}
} else {
encryptFields(requestObj);
}
}
private void encryptFields(Object obj) throws IllegalAccessException {
Field[] fields = obj.getClass().getDeclaredFields();
for (Field field : fields) {
boolean hasSecureField = field.isAnnotationPresent(Dataprocess.class);
if (hasSecureField) {
field.setAccessible(true);
String plaintextValue = (String) field.get(obj);
String encryptValue = AseUtil.encrypt(plaintextValue, secretKey);
field.set(obj, encryptValue);
}
}
}
private Object handleDecrypt(Object responseObj) throws IllegalAccessException {
if (Objects.isNull(responseObj)) {
return null;
}
if (responseObj instanceof List) {
List<Object> responseList = (List<Object>) responseObj;
for (Object obj : responseList) {
decryptFields(obj);
}
} else {
decryptFields(responseObj);
}
return responseObj;
}
private void decryptFields(Object obj) throws IllegalAccessException {
Field[] fields = obj.getClass().getDeclaredFields();
for (Field field : fields) {
boolean hasSecureField = field.isAnnotationPresent(Dataprocess.class);
if (hasSecureField) {
field.setAccessible(true);
String encryptValue = (String) field.get(obj);
String plaintextValue = AseUtil.decrypt(encryptValue, secretKey);
field.set(obj, plaintextValue);
}
}
}
}
如何使用
把@DataProcess加在需要自动加解密的字段上
@MethodProcess加在需要加解密的方法上
效果展示
加密
解密
demo地址(最新代码在dev分支)