1:自定义注解
/**
* 脱敏注解
**/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@JacksonAnnotationsInside
@JsonSerialize(using = SensitiveSerialize.class)
public @interface Sensitive {
/**
* 脱敏数据类型
*/
SensitiveTypeEnum type();
}
2:序列化
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.thk.utils.SensitiveUtils;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import java.io.IOException;
import java.util.Objects;
/**
* 脱敏序列化
*/
@NoArgsConstructor
@AllArgsConstructor
public class SensitiveSerialize extends JsonSerializer<String> implements ContextualSerializer {
private SensitiveTypeEnum type;
@Override
public void serialize(final String originStr, final JsonGenerator jsonGenerator,
final SerializerProvider serializerProvider) throws IOException {
switch (type) {
case CHINESE_NAME:
jsonGenerator.writeString( SensitiveUtils.chineseName(originStr));
break;
case MOBILE_PHONE:
jsonGenerator.writeString(SensitiveUtils.mobilePhone(originStr));
break;
case EMAIL:
jsonGenerator.writeString(SensitiveUtils.email(originStr));
break;
case PASSWORD:
jsonGenerator.writeString(SensitiveUtils.password(originStr));
break;
case KEY:
jsonGenerator.writeString(SensitiveUtils.key(originStr));
break;
default:
throw new IllegalArgumentException("未定义的敏感信息枚举类" + type);
}
}
@Override
public JsonSerializer<?> createContextual(final SerializerProvider serializerProvider, final BeanProperty beanProperty) throws JsonMappingException {
if (beanProperty != null) {
if (Objects.equals(beanProperty.getType().getRawClass(), String.class)) {
Sensitive sensitive = beanProperty.getAnnotation(Sensitive.class);
if (sensitive == null) {
sensitive = beanProperty.getContextAnnotation(Sensitive.class);
}
if (sensitive != null) {
return new SensitiveSerialize(sensitive.type());
}
}
return serializerProvider.findValueSerializer(beanProperty.getType(), beanProperty);
}
return serializerProvider.findNullValueSerializer(null);
}
}
3:脱敏类型枚举类
public enum SensitiveTypeEnum {
/**
* 用户名, 唐*天, 李*
*/
CHINESE_NAME,
/**
* 手机号, 17623****78
*/
MOBILE_PHONE,
/**
* 电子邮件, 2423*****8@qq.com
*/
EMAIL,
/**
* 密码, ******
*/
PASSWORD,
/**
* 密钥最后三位其他都是***
*/
KEY
}
4:使用方法,用在实体类上,对昵称,邮箱,电话,进行脱敏处理
public class People {
private Integer bizCode;
@NotNull(message = "id不能为空")
private Long id;
private String name;
private Integer age;
private String address;
@Sensitive(type = SensitiveTypeEnum.CHINESE_NAME)
private String userName;
private String pwd;
@Sensitive(type = SensitiveTypeEnum.EMAIL)
private String email;
@Sensitive(type = SensitiveTypeEnum.MOBILE_PHONE)
private String phonenumber;
private String sex;
}
5:postman测试