給敏感字符加星號處理

支持不一樣長度的字符串,自動加星號處理:加密

    /**
     * 敏感數據加*號處理
     *
     * @param info 要加密的字符串
     */
    public static String replaceSecretInfo(String info) {
        if (info.isEmpty()) {
            return "";
        }
        String result;
        int infoLength = info.length();
        if (infoLength == 1) {
            result = "*";
        } else if (infoLength == 2) {
            result = info.substring(0,1) + "*";
        } else {
            double tempNum = (double) infoLength / 3;
            Integer num1 = (int) Math.floor(tempNum);
            Integer num2 = (int) Math.ceil(tempNum);
            Integer num3 = infoLength - num1 - num2;
            String star = StringUtils.repeat("*", num2);
            String regex = "(.{" + num1 + "})(.{" + num2 + "})(.{" + num3 + "})";
            String replacement = "$1" + star + "$3";
            result = info.replaceAll(regex, replacement);
        }
        return result;
    }
相關文章
相關標籤/搜索