在大量参考作者:l_learning文章的基础上,对脱敏注解进行了进一步的优化和完善。

1.脱敏注解(同步作者: l_learning)

/**
 * Title: com.common.core.annotation
 * Description:脱敏注解
 * Copyright: Copyright (c) 2024
 * Company:
 *
 * @author :mingF
 * @version :3.2.2
 * @date :2024/4/22 16:02
 */
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotationsInside
@JsonSerialize(using = DesensitizationJsonSerializer.class)
public @interface Desensitization {

    Class<? extends AbstractDesensitization> value();
}

2.脱敏父类(同步作者: l_learning)

/**
 * Title: com.common.core.desensitization
 * Description:脱敏父类
 * Copyright: Copyright (c) 2024
 * Company:
 *
 * @author :mingF
 * @version :3.2.2
 * @date :2024/4/22 16:08
 */
public abstract  class AbstractDesensitization {
    /**
     * @description : 脱敏
     * @author : mingF
     * @date : 2024/4/22 16:08
     * @return :null
    **/
    public abstract String serialize(String value);
}

3.脱敏序列化(同步作者: l_learning)

/**
 * Title: com.common.core.desensitization.jsonSerializer
 * Description:脱敏序列化
 * Copyright: Copyright (c) 2024
 * Company:
 *
 * @author :mingF
 * @version :3.2.2
 * @date :2024/4/22 16:10
 */
public class DesensitizationJsonSerializer extends JsonSerializer<String> implements ContextualSerializer {

    private AbstractDesensitization desensitization;

    public DesensitizationJsonSerializer() {
    }

    public DesensitizationJsonSerializer(AbstractDesensitization desensitization) {
        this.desensitization = desensitization;
    }

    @Override
    public void serialize(String s, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        jsonGenerator.writeString(desensitization.serialize(s));
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty) throws JsonMappingException {
        JsonSerializer<?> jsonSerializer = null;
        if(null == beanProperty) jsonSerializer = serializerProvider.findNullValueSerializer(beanProperty);

        if(!Objects.equals(beanProperty.getType().getRawClass(), String.class))
            jsonSerializer = serializerProvider.findValueSerializer(beanProperty.getType(), beanProperty);

        if(Objects.equals(beanProperty.getType().getRawClass(), String.class)){
            jsonSerializer = setDesensitization(jsonSerializer, beanProperty);
        }
        return jsonSerializer;
    }

    /**
     * 设置脱敏
     * @param beanProperty
     * @return
     */
    private JsonSerializer<?> setDesensitization(JsonSerializer<?> jsonSerializer, BeanProperty beanProperty) {
        Desensitization desensitization = beanProperty.getAnnotation(Desensitization.class);

        if (desensitization == null) desensitization = beanProperty.getContextAnnotation(Desensitization.class);

        if (desensitization != null) {
            //设置脱敏实例
            try {
                jsonSerializer = new DesensitizationJsonSerializer(desensitization.value().newInstance());
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return jsonSerializer;
    }
}

主要在参考原作者的基础上,对名字,邮箱,电话进行了脱敏优化处理

4.姓名脱敏(优化),增加了英文名脱敏

/**
 * Title: com.common.core.desensitization.impl
 * Description:姓名脱敏
 * Copyright: Copyright (c) 2024
 * Company:
 *
 * @author :mingF
 * @version :3.2.2
 * @date :2024/4/22 16:14
 */
public class NameDesensitization extends AbstractDesensitization {
    @Override
    public String serialize(String value) {
        String serializeValue = "";
        if(isEnglish(value)){
            // 定义英文字符的正则表达式
            String regex = "[a-zA-Z]";
            // 使用正则表达式匹配字符串中的英文字符
            StringBuilder resultBuilder = new StringBuilder();
            // 使用正则表达式匹配字符串中的英文字符
            Matcher matcher = Pattern.compile(regex).matcher(value);
            int count = 0;
            while (matcher.find()) {
                String group = matcher.group();
                count++;
                // 如果匹配到的英文字符数量大于等于3
                if (count >= 3) {
                    // 判断是不是第一个字符或最后一个字符
                    if (count <= 2 || !matcher.find()) {
                        // 如果是第一个字符或最后一个字符,不进行替换
                        resultBuilder.append(group);
                    } else {
                        // 否则,在第一个字符和最后一个字符之间换成*
                        resultBuilder.append("*");
                    }
                } else {
                    // 如果匹配到的英文字符数量小于3,将中间一个字符替换为*
                    if (count == 2 && matcher.find()) {
                        resultBuilder.append("*");
                    }
                    resultBuilder.append(group);
                }
            }
            serializeValue = resultBuilder.toString();
        }else {
            if(value.length() < 3){
                serializeValue = value.replaceAll(".*(?=[\\u4e00-\\u9fa5])","*");
            }else{
                serializeValue = value.replaceAll("(?<=[\\u4e00-\\u9fa5]).*(?=[\\u4e00-\\u9fa5])","*");
            }
        }


        return serializeValue;
    }

    public static boolean isEnglish(String s) {
        return s.matches(".*[a-zA-Z]+.*");
    }

5.手机号脱敏(优化),增加了特殊号码脱敏

/**
 * Title: com.common.core.desensitization.impl
 * Description:手机号脱敏
 * Copyright: Copyright (c) 2024
 * Company:
 *
 * @author :mingF
 * @version :3.2.2
 * @date :2024/4/22 16:15
 */
public class MobilePhoneDesensitization extends AbstractDesensitization {
    @Override
    public String serialize(String value) {
        return formatPhoneNumber(value);
    }
    public static String formatPhoneNumber(String value) {
        // 匹配电话号码中的数字部分,支持多种分隔符和不带分隔符的情况
        Pattern pattern = Pattern.compile("(\\d{3})[-\\s]*(\\d{4})[-\\s]*(\\d{4})");
        Matcher matcher = pattern.matcher(value);

        // 如果找到匹配的内容,则进行替换
        if (matcher.find()) {
            // 使用正则替换的方法将匹配到的部分替换为 "****",保留其他部分
            return value.replaceAll("(\\d{3})[-\\s]*(\\d{4})[-\\s]*(\\d{4})", "$1****$2 $3");