package com.project.common.utils;
|
|
import com.project.common.annotation.Sensitive;
|
|
import java.lang.reflect.Field;
|
import java.util.regex.Pattern;
|
|
/**
|
* 功能描述:
|
*
|
* @author ZQN
|
* @version 1.0 2025-03-25 17:04
|
*/
|
public class SensitiveUtil {
|
|
public static Object desensitize(Object obj) {
|
if (obj == null) {
|
return null;
|
}
|
Class<?> clazz = obj.getClass();
|
Field[] fields = clazz.getDeclaredFields();
|
for (Field field : fields) {
|
if (field.isAnnotationPresent(Sensitive.class)) {
|
Sensitive sensitive = field.getAnnotation(Sensitive.class);
|
field.setAccessible(true);
|
try {
|
Object value = field.get(obj);
|
if (value != null && value instanceof String) {
|
String strValue = (String) value;
|
String desensitizedValue = desensitizeByType(strValue, sensitive.type());
|
field.set(obj, desensitizedValue);
|
}
|
} catch (IllegalAccessException e) {
|
e.printStackTrace();
|
}
|
}
|
}
|
return obj;
|
}
|
|
private static String desensitizeByType(String value, Sensitive.SensitiveType type) {
|
switch (type) {
|
case PHONE:
|
return desensitizePhone(value);
|
case EMAIL:
|
return desensitizeEmail(value);
|
case ID_CARD:
|
return desensitizeIdCard(value);
|
default:
|
return desensitizeDefault(value);
|
}
|
}
|
|
private static String desensitizeDefault(String value) {
|
if (value.length() <= 1) {
|
return value;
|
}
|
StringBuilder sb = new StringBuilder();
|
sb.append(value.charAt(0));
|
if (value.length() > 2) {
|
for (int i = 0; i < value.length() - 2; i++) {
|
sb.append("*");
|
}
|
sb.append(value.charAt(value.length() - 1));
|
} else {
|
sb.append("*");
|
}
|
return sb.toString();
|
}
|
|
private static String desensitizePhone(String phone) {
|
if (Pattern.matches("^\\d{11}$", phone)) {
|
return phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
|
}
|
return phone;
|
}
|
|
private static String desensitizeEmail(String email) {
|
if (email.contains("@")) {
|
String[] parts = email.split("@");
|
String name = parts[0];
|
if (name.length() <= 1) {
|
return email;
|
}
|
StringBuilder sb = new StringBuilder();
|
sb.append(name.charAt(0));
|
for (int i = 0; i < name.length() - 2; i++) {
|
sb.append("*");
|
}
|
sb.append(name.charAt(name.length() - 1));
|
return sb.toString() + "@" + parts[1];
|
}
|
return email;
|
}
|
|
private static String desensitizeIdCard(String idCard) {
|
if (Pattern.matches("^\\d{18}$", idCard)) {
|
return idCard.replaceAll("(\\d{4})\\d{10}(\\d{4})", "$1**********$2");
|
}
|
return idCard;
|
}
|
}
|