springboot 注解+切面实现数据脱敏
创建脱敏类型枚举
public enum SensitiveTypeEnum {
CHINESE_NAME,
ID_CARD,
FIXED_PHONE,
MOBILE_PHONE,
ADDRESS,
EMAIL,
BANK_CARD,
CNAPS_CODE;
}
脱敏注解
@Inherited
@Documented
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Desensitized {
SensitiveTypeEnum type();
}
脱敏工具类
package com.huang.mybatisplus.annotation;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huang.mybatisplus.http.Response;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.*;
@Slf4j
public class DesensitizedUtil {
public static final String DESENT_STATUS = "1";
public static void desentData(Object obj) throws IllegalAccessException {
if (null == obj) {
return;
}
if (obj.getClass().isPrimitive()) {
return;
}
if (obj.getClass().isInterface()) {
return;
}
Object data = null;
Class<?> clazz = null;
Field[] fields = null;
if (obj.getClass().equals(Response.class)) {
data = ((Response) obj).getData();
clazz = data.getClass();
if (null == clazz) {
return;
}
fields = clazz.getDeclaredFields();
} else {
data = obj;
clazz = obj.getClass();
fields = obj.getClass().getDeclaredFields();
}
while (null != clazz.getSuperclass() && !Object.class.equals(clazz.getSuperclass())) {
fields = (Field[]) ArrayUtils.addAll(fields, clazz.getSuperclass().getDeclaredFields());
clazz = clazz.getSuperclass();
}
if (null == fields && fields.length == 0) {
return;
}
for (Field field : fields) {
field.setAccessible(true);
if (null == field) {
return;
}
Object value = field.get(data);
if (null != value) {
Class<?> type = value.getClass();
if (type.isArray()) {
int len = Array.getLength(value);
for (int i = 0; i < len; i++) {
Object arrayObject = Array.get(value, i);
DesensitizedUtil.desentData(arrayObject);
}
} else if (value instanceof Collection<?>) {
Collection<?> c = (Collection<?>) value;
Iterator<?> it = c.iterator();
while (it.hasNext()) {
Object collectionObj = it.next();
DesensitizedUtil.desentData(collectionObj);
}
} else if (value instanceof Map<?, ?>) {
Map<?, ?> m = (Map<?, ?>) value;
Set<?> set = m.entrySet();
for (Object o : set) {
Map.Entry<?, ?> entry = (Map.Entry<?, ?>) o;
Object mapVal = entry.getValue();
DesensitizedUtil.desentData(mapVal);
}
} else if (!type.isPrimitive()
&& !StringUtils.startsWith(type.getPackage().getName(), "javax.")
&& !StringUtils.startsWith(type.getPackage().getName(), "java.")
&& !StringUtils.startsWith(field.getType().getName(), "javax.")
&& !StringUtils.startsWith(field.getName(), "java.")) {
DesensitizedUtil.desentData(type);
}
}
Desensitized annotation = field.getDeclaredAnnotation(Desensitized.class);
if (field.getType().equals(String.class) && null != annotation) {
String valueStr = (String) field.get(data);
if (StringUtils.isNotBlank(valueStr)) {
switch (annotation.type()) {
case CHINESE_NAME: {
field.set(data, DesensitizedUtil.chineseName(valueStr));
break;
}
case ID_CARD: {
field.set(data, DesensitizedUtil.idCardNum(valueStr));
break;
}
case FIXED_PHONE: {
field.set(data, DesensitizedUtil.fixedPhone(valueStr));
break;
}
case MOBILE_PHONE: {
field.set(data, DesensitizedUtil.mobilePhone(valueStr));
break;
}
case ADDRESS: {
field.set(data, DesensitizedUtil.address(valueStr, 4));
break;
}
case EMAIL: {
field.set(data, DesensitizedUtil.email(valueStr));
break;
}
case BANK_CARD: {
field.set(data, DesensitizedUtil.bankCard(valueStr));
break;
}
case CNAPS_CODE: {
field.set(data, DesensitizedUtil.cnapsCode(valueStr));
break;
}
default: {
break;
}
}
}
}
}
}
private static String chineseName(String fullName) {
if (StringUtils.isBlank(fullName)) {
return "";
}
String name = StringUtils.left(fullName, 1);
return StringUtils.rightPad(name, StringUtils.length(fullName), "*");
}
private static String chineseName(String familyName, String givenName) {
if (StringUtils.isBlank(familyName) || StringUtils.isBlank(givenName)) {
return "";
}
return chineseName(familyName + givenName);
}
private static String idCardNum(String id) {
if (StringUtils.isBlank(id)) {
return "";
}
String num = StringUtils.right(id, 4);
return StringUtils.leftPad(num, StringUtils.length(id), "*");
}
private static String fixedPhone(String num) {
if (StringUtils.isBlank(num)) {
return "";
}
return StringUtils.leftPad(StringUtils.right(num, 4), StringUtils.length(num), "*");
}
private static String mobilePhone(String num) {
if (StringUtils.isBlank(num)) {
return "";
}
return StringUtils.left(num, 3).concat(StringUtils.removeStart(StringUtils.leftPad(StringUtils.right(num, 4), StringUtils.length(num), "*"), "***"));
}
private static String address(String address, int sensitiveSize) {
if (StringUtils.isBlank(address)) {
return "";
}
int length = StringUtils.length(address);
return StringUtils.rightPad(StringUtils.left(address, length - sensitiveSize), length, "*");
}
private static String email(String email) {
if (StringUtils.isBlank(email)) {
return "";
}
int index = StringUtils.indexOf(email, "@");
if (index <= 1) {
return email;
} else {
return StringUtils.rightPad(StringUtils.left(email, 1), index, "*").concat(StringUtils.mid(email, index, StringUtils.length(email)));
}
}
private static String bankCard(String cardNum) {
if (StringUtils.isBlank(cardNum)) {
return "";
}
return StringUtils.left(cardNum, 6).concat(StringUtils.removeStart(StringUtils.leftPad(StringUtils.right(cardNum, 4), StringUtils.length(cardNum), "*"), "******"));
}
private static String cnapsCode(String code) {
if (StringUtils.isBlank(code)) {
return "";
}
return StringUtils.rightPad(StringUtils.left(code, 2), StringUtils.length(code), "*");
}
}
添加是否需要脱敏,方法注解
import java.lang.annotation.*;
@Inherited
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ToSensitive {
boolean isSensitive() default true;
}
切面
import com.huang.mybatisplus.annotation.DesensitizedUtil;
import com.huang.mybatisplus.annotation.ToSensitive;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
@Order(1)
@Aspect
@Slf4j
@Component
public class SensitiveAspect {
@Around("execution(public * com.huang.*.controller.*.*(..))")
public Object sensitiveClass(ProceedingJoinPoint joinPoint) throws Throwable {
return sensitiveFormat(joinPoint);
}
public Object sensitiveFormat(ProceedingJoinPoint joinPoint) throws Throwable {
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Method method = methodSignature.getMethod();
if (!method.isAnnotationPresent(ToSensitive.class)) {
log.info("不需要切面");
Object result = joinPoint.proceed();
return result;
}
ToSensitive toSensitive = method.getAnnotation(ToSensitive.class);
if (!toSensitive.isSensitive()){
log.info("不需要切面脱敏");
Object result = joinPoint.proceed();
return result;
}
Object obj = joinPoint.proceed();
if (obj == null || isPrimitive(obj.getClass())) {
return obj;
}
if (DesensitizedUtil.DESENT_STATUS.equals("1")) {
DesensitizedUtil.desentData(obj);
}
return obj;
}
public static boolean isPrimitive(Class<?> clz) {
try {
if (String.class.isAssignableFrom(clz) || clz.isPrimitive()) {
return true;
} else {
return ((Class) clz.getField("TYPE").get(null)).isPrimitive();
}
} catch (Exception e) {
return false;
}
}
}
统一结果集和返回值
@Data
@Component
public class Response<T> {
public static ResponseCode responseCode;
public String message;
public T data;
public String code;
public Response(String code, String message, T data) {
this.message = message;
this.code = code;
this.data = data;
}
public Response(String code, String msg) {
this.message = msg;
this.code = code;
}
@Autowired
public Response(ResponseCode responseCode) {
Response.responseCode = responseCode;
}
public static <T> Response<T> success(String successMessage, T data) {
return new Response<>(responseCode.getSuccessCode(), successMessage, data);
}
public static <T> Response<T> fail(String errorMessage) {
return new Response<>(responseCode.getErrorCode(), errorMessage);
}
}
@Data
@Component
public class ResponseCode {
public String successCode = "200";
public String errorCode = "500";
public String authErrorCode = "300";
}
实体类添加注解
@Data
@TableName("site")
@ApiModel(value = "Site对象", description = "")
public class Site implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "网点ID")
@TableId(value = "id", type = IdType.INPUT)
private Long id;
@Desensitized(type = SensitiveTypeEnum.CHINESE_NAME)
@ApiModelProperty(value = "网点名称")
private String name;
@Desensitized(type = SensitiveTypeEnum.MOBILE_PHONE)
@ApiModelProperty(value = "网点电话")
private String tel;
}
controller 添加注解
@ToSensitive(isSensitive = true)
@GetMapping("/site/page")
public Response<Page<Site>> pageSiteBy() {
Page<Site> page = siteService.page(new Page<>(0, 3));
return Response.success("成功", page);
}
测试结果