一、对一些敏感数据进行脱敏,使用正则表达式:
1 public class RptUtils {
2 /**
3 * 金额脱敏
4 * @param money
5 * @return
6 */
7 public static String maskAll(String money){
8 //保留0个数到0个结束,$1第一个表达式、$2第二个表达式,中间*号可以是任意值
9 return money.replaceAll("(\\w{0})\\w*(\\w{0})","$1***$2");
10 }
11
12 // 手机号码中间四位数字脱敏
13 public static String mobileEncrypt(String mobile){
14 return mobile.replaceAll("(\\d{3})\\d{4}(\\d{4})","$1*****$2");
15 }
16
17 //身份证号脱敏
18 public static String idEncrypt(String id){
19 return id.replaceAll("(?<=\\w{3})\\w(?=\\w{4})","*");
20 }
21
22
23 //邮箱信息脱敏
24 public static String getEmail(String email){
25 return email.replaceAll("(\\w+)\\w{5}@(\\w+)","$1***@$2");
26 }
27
28 }方法调用:
@Override
public List<List<Object>> selectSysCrmDeptCollectionCount(String startTime, String endTime) {
List<Map<String, Object>> maps = countMapper.selectSysCrmDeptCollectionCount(startTime, endTime);
for (int i = 0; i < maps.size(); i++){
Map<String, Object> objects = maps.get(i);
String str = RptUtils.getMoney(objects.get("money").toString());
String money = str.substring(0, str.indexOf("."));
System.out.println(money);
objects.put("money", money);
}
return RptUtils.convert(maps);
}
注:另外一种写法:(推荐)
1 public class RptUtils {
2
3 private static final String SYMBOL = "*";
4
5 /**
6 * 脱敏
7 * @param str 待脱敏字符串
8 * @param left 左边保留多少位
9 * @param right 右边保留多少位
10 * @return 脱敏结果,除左右外,其余字符将被替换为*
11 */
12 public static String around(String str, int left, int right){
13 if (str == null || (str.length() < left + right +1)){
14 return str;
15 }
16 String regex = String.format("(?<=\\w{%d})\\w(?=\\w{%d})", left, right);
17 return str.replaceAll(regex, SYMBOL);
18 }
19
20 /**
21 * 正则表达式实现金额数据脱敏
22 * @param money
23 * @return
24 */
25 public static String getMoney(String money){
26 //保留0个数到0个结束
27 return around(money,0,0);
28 }
29 }业务层调用:
//业务层调用
@Override
public List<List<Object>> selectSysCrmDeptCollectionCount(String startTime, String endTime) {
List<Map<String, Object>> maps = countMapper.selectSysCrmDeptCollectionCount(startTime, endTime);
for (int i = 0; i < maps.size(); i++){
Map<String, Object> objects = maps.get(i);
String money = objects.get("money").toString();
double v = Double.parseDouble(money);
if(v != 0){
String money1 = RptUtils.getMoney(String.valueOf(v));
String str = money1.substring(0, money1.indexOf("."));
objects.put("money", str);
}else if(v == 0){
String s = "" + v;
//Constants.NOTHING 中的常量,if v代表(金额) == 0 的话 s.replaceAll(s,Constants.NOTHING)
就是把金额为0 的 替换成 “无”
String str = s.replaceAll(s, Constants.NOTHING);
objects.put("money", str);
}
}
} return RptUtils.convert(maps); }

















