自定义脱敏注解
package com.huiye.core.annotations; import com.fasterxml.jackson.annotation.JacksonAnnotationsInside; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.huiye.core.enums.DesensitizedType; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 数据脱敏注解,表示这个注解用于属性上。SensitiveJsonSerializer类进行处理序列化 **/ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) @JacksonAnnotationsInside @JsonSerialize(using = SensitiveJsonSerializer.class) public @interface Sensitive { DesensitizedType desensitizedType(); }
序列化过滤
package com.huiye.core.annotations; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.BeanProperty; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.ser.ContextualSerializer; import com.huiye.core.enums.DesensitizedType; import java.io.IOException; import java.util.Objects; /** * 数据脱敏序列化过滤 * */ public class SensitiveJsonSerializer extends JsonSerializer<String> implements ContextualSerializer { private DesensitizedType desensitizedType; @Override public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException { gen.writeString(desensitizedType.desensitizer().apply(value)); } @Override public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException { Sensitive annotation = property.getAnnotation(Sensitive.class); if (Objects.nonNull(annotation) && Objects.equals(String.class, property.getType().getRawClass())) { this.desensitizedType = annotation.desensitizedType(); return this; } return prov.findValueSerializer(property.getType(), property); } }
脱敏类型枚举,不同的类型处理脱密的数据不同。
package com.huiye.core.enums; import java.util.function.Function; /** * 脱敏类型,不同的类型处理脱密的数据不同。 */ public enum DesensitizedType { /** * 姓名,第2位星号替换 */ USERNAME(s -> s.replaceAll("(\\S)\\S(\\S*)", "$1*$2")), /** * 身份证,中间10位星号替换 */ ID_CARD(s -> s.replaceAll("(\\d{4})\\d{10}(\\d{4})", "$1** **** ****$2")), /** * 手机号,中间4位星号替换 */ PHONE(s -> s.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2")), /** * 电子邮箱,仅显示第一个字母和@后面的地址显示,其他星号替换 */ EMAIL(s -> s.replaceAll("(^.)[^@]*(@.*$)", "$1****$2")), /** * 银行卡号,保留最后4位,其他星号替换 */ BANK_CARD(s -> s.replaceAll("\\d{15}(\\d{3})", "**** **** **** **** $1")); private final Function<String, String> desensitizer; DesensitizedType(Function<String, String> desensitizer) { this.desensitizer = desensitizer; } // 获取脱密类型。 public Function<String, String> desensitizer() { return desensitizer; } }
使用注解
@Sensitive(desensitizedType=DesensitizedType.PHONE) private String phone;
标签:DesensitizedType,jackson,实现,com,import,数据,annotation,脱敏,fasterxml From: https://www.cnblogs.com/yylucky666/p/18435158