自定义字段加密注解
该注解实现,在接口返回时,对指定字段值进行加密操作。
定义注解
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.TYPE})
public @interface DataEncrypt {
}
自定义ObjectMapper
@Configuration
public class ObjectMapperConfig {
@Bean
@Primary
ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
ObjectMapper mapper = builder.createXmlMapper(false).build();
AnnotationIntrospector sis = mapper.getSerializationConfig().getAnnotationIntrospector();
AnnotationIntrospector is1 = AnnotationIntrospector.pair(sis, new DataAnnotationIntrospector());
mapper.setAnnotationIntrospector(is1);
return mapper;
}
}
自定义绑定序列化类和相关字段的关联关系
public class DataAnnotationIntrospector extends NopAnnotationIntrospector {
@Override
public Object findSerializer(Annotated am){
DataEncrypt annotation = am.getAnnotation(DataEncrypt.class);
if (annotation != null) {
return DataSerializer.class
}
return null;
}
}
自定义标准序列化类对具体的字段进行加密处理
AESUtil为自行实现的加密工具类
public class DataSerializer extends StdSerializer<Object> {
public DataSerializer() {
super(Object.class);
}
@Override
public void serialize(Object value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) {
if (value == null) return;
try {
// 拿到request 就可以根据接口来决定是否进行该注解的处理
// HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String encryptStr = AESUtil.encrypt(value.toString());
jsonGenerator.writeString(encryptStr );
} catch (Exception e) {
}
}
}
注解加在字段上进行使用
@DataEncrypt
private String phone;
接口返回数据中,对应的phone值为加密值。