字段加密注解

字段加密注解,第1张

自定义字段加密注解 该注解实现,在接口返回时,对指定字段值进行加密 *** 作。

定义注解

@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 {
	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 username;

接口返回数据中,对应的username值为加密值。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/919598.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-16
下一篇 2022-05-16

发表评论

登录后才能评论

评论列表(0条)