一、對一些敏感數據進行脫敏,使用正則表達式:
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); }