这是我根据网上资料整理的两种数据脱敏解决方案,各有千秋,都在我都实际环境中使用了,来自网络,回归网络,希望对读到的朋友有帮助。废话少说,下面就开始贴代码
/**
* 脱敏注解
*
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Desensitization {
/**
* 脱敏规则类型
* @return
*/
DesensitionType type();
/**
* 附加值, 自定义正则表达式等
* @return
*/
String[] attach() default "";
}
/**
* 脱敏规则枚举
*
*/
public enum DesensitionType {
PHONE("phone", "11位手机号", "^(\\d{3})\\d{4}(\\d{4})$", "$1****$2"),
//注意后四位的表达式,因为有的身份证最后一位是X
ID_CARD("idCard", "16或者18身份证号", "^(\\d{4})\\d{8,10}(\\w{4})$", "$1****$2"),
BANK_CARD("bankCardNo", "银行卡号", "^(\\d{4})\\d*(\\d{4})$", "$1****$2"),
REAL_NAME("realName","真实姓名","(?<=.{1}).*(?=.{1})","*"),
EMAIL("email","电子邮箱","(\\w+)\\w{5}@(\\w+)", "$1***@$2"),
CUSTOM("custom", "自定义正则处理", ""),
TRUNCATE("truncate", "字符串截取处理", ""),
;
String type;
String describe;
String[] regular;
DesensitionType(String type, String describe, String... regular) {
this.type = type;
this.describe = describe;
this.regular = regular;
}
public String getType() {
return type;
}
public String getDescribe() {
return describe;
}
public String[] getRegular() {
return regular;
}
}
上面两个类是为了在实体类属性上注解使用的
1.基于mybatis的数据脱敏实现
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.he.annotation.DesensitionType;
import cn.he.annotation.Desensitization;
/**
* mybatis脱敏处理
*
* @author 傻根她弟
*
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
@Intercepts({
@Signature(type = Executor.class, method = "query", args = { MappedStatement.class, Object.class,
RowBounds.class, ResultHandler.class }),
@Signature(type = Executor.class, method = "query", args = { MappedStatement.class, Object.class,
RowBounds.class, ResultHandler.class, Cac