脱敏工具类
脱敏工具类:
public class DesensitizationUtils { /** * 字符串脱敏,通用 * @param subPre 截取前几位 * @param subSuffix 截取后几位 * @param replaceStr 补充码 * @param padCount 补充码数 * @param targetStr 目标字符串 * @return java.lang.String */ public static String getDesensitization(Integer subPre,Integer subSuffix, String replaceStr, Integer padCount, String targetStr){ if(StringUtils.isBlank(targetStr)){ return null; } String pre = targetStr.substring(0,subPre); String suffix = targetStr.substring(targetStr.length() - subSuffix,targetStr.length()); String leftPadResult = StringUtils.leftPad(suffix,padCount,replaceStr); String result = pre + leftPadResult; return result; } /** * 脱敏字符串 * 1.>8,固定*为4位,后四位显示,前=len-(4+4) * 2.<=8,固定*为len/2,剩余的restLen为len-*的len,如果restLen能整除2,则lLen与rLen均分;如果restLen不能整除2,则lLen=restLen/2 + 1,rLen=restLen/2。 * @param targetStr 目标字符串 * @return java.lang.String */ public static String desensitizedCommon(String targetStr){ if(StringUtils.isBlank(targetStr)){ return targetStr; } int len = targetStr.length(); if(len > 8){ // 固定*为4位,后四位显示,前=len-(4+4) return getDesensitization(len-8,4,"*",8,targetStr); } if(len <= 8){ // 固定*为len/2,剩余的restLen为len-*的len,如果restLen能整除2,则lLen与rLen均分;如果restLen不能整除2,则lLen=restLen/2 + 1,rLen=restLen/2。 int padLen = len/2; int restLeh = len - padLen; int rLen; int lLen; int average = restLeh/2; if(restLeh % 2 == 0){ lLen = average; }else{ lLen = average + 1; } rLen = average; // padCount = *的len+rLen int padCount = padLen + rLen; return getDesensitization(lLen,rLen,"*",padCount,targetStr); } return targetStr; } public static void main(String[] args) { System.out.println(desensitizedCommon("13520096531")); } }
测试结果: