本文主要是介绍Spring 数据脱敏实现方式,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1、前言
当前互联网中,越来越重视数据安全,数据脱敏在实际应用中越来越多。
2 、脱敏方式
2.1 数据库sql 语句脱敏
sql 语句脱敏是比较传统通用的,例子如下所示:
select CONCAT(LETF(mobile,3),"*****",RIGHT(mobile,3)) from tb_user
2.2 通过Java 代码脱敏
代码脱敏一般要通过aop以及自定义注解实现,代码如下。
package com.example.demo.annotion;import java.lang.annotation.*;@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DesensitizationWord {}
package com.example.demo.annotion;import java.lang.annotation.*;@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DesensitizationWord {}
@Aspect
@Component
@Slf4j
public class DesensitizationgWordAspect {@Pointcut(value = "@annotation(com.example.demo.annotion.DesensitizationWord)")public void desensitizationgWordFlag() {}@AfterReturning(value = "desensitizationgWordFlag()",returning = "result")public void afterReturning(JoinPoint joinPoint, Object result) throws IllegalAccessException {if(result instanceof Base){Base base = (Base)result;List<?> list = base.getData();if(CollectionUtils.isEmpty(list)) return;for(Object objcet:list){Field[] fields = objcet.getClass().getDeclaredFields();for(Field field:fields){Annotation[] annotations = field.getAnnotations();if(annotations!=null && annotations.length>0){for (Annotation annotation:annotations ){field.setAccessible(true);if(annotation instanceof Mobile){Object mobile = field.get(objcet);if(mobile instanceof String){String mobileString= (String)mobile;field.set(objcet,desensitizedPhoneNumber(mobileString));}}}}}}}}public String desensitizedPhoneNumber(String phoneNumber) {if (StringUtils.isNotBlank(phoneNumber)) {phoneNumber = phoneNumber.replaceAll("(\\w{3})\\w*(\\w{3})", "$1*****$2");}return phoneNumber;}
}
2.3 、通过mybatis-mate-sensitive-jackson
这个是mybaitsplus 的功能,其实实现的原理和2.2的的方法类型,只是它封装成jar包,并且支持扩展。 怎么使用大家可以参考企业高级特性 | MyBatis-Plus,它目前支持如下脱敏规则如
package mybatis.mate.strategy;public interface SensitiveType {String chineseName = "chineseName";String idCard = "idCard";String phone = "phone";String mobile = "mobile";String address = "address";String email = "email";String bankCard = "bankCard";String password = "password";String carNumber = "carNumber";
}
还可以自定义脱敏规则,如下代码
@Configuration
public class SensitiveStrategyConfig {/*** 注入脱敏策略*/@Beanpublic ISensitiveStrategy sensitiveStrategy() {// 自定义 testStrategy 类型脱敏处理return new SensitiveStrategy().addStrategy("testStrategy", t -> t + "***test***");}
}
这篇关于Spring 数据脱敏实现方式的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!