数据脱敏 sql及java代码实现

1 sql 实现:

-- 电话号码脱敏sql:
 
SELECT mobilePhone AS 脱敏前电话号码,CONCAT(LEFT(mobilePhone,3), '********' ) AS 脱敏后电话号码 FROM t_s_user
 
-- 身份证号码脱敏sql:
 
SELECT idcard AS 未脱敏身份证, CONCAT(LEFT(idcard,3), '****' ,RIGHT(idcard,4)) AS 脱敏后身份证号 FROM t_s_user

2 java 实现

方式1

import java.util.Arrays;
import java.util.List;

/**
 * 数据脱敏工具
 */
public class DesensitizedUtil {

    /**
     * 复姓
     */
    public static final List<String> compoundSurnames= Arrays.asList(new String[]{"欧阳","太史","端木","上官","司马","东方","独孤","南宫","万俟","闻人","夏侯","诸葛","尉迟","公羊","赫连","澹台","皇甫","宗政","濮阳","公冶","太叔","申屠","公孙","慕容","仲孙","钟离","长孙","宇文","司徒","鲜于","司空","闾丘","子车","亓官","司寇","巫马","公西","颛孙","壤驷","公良","漆雕","乐正","宰父","谷梁","拓跋","夹谷","轩辕","令狐","段干","百里","呼延","东郭","南门","羊舌","微生","公户","公玉","公仪","梁丘","公仲","公上","公门","公山","公坚","左丘","公伯","西门","公祖","第五","公乘","贯丘","公皙","南荣","东里","东宫","仲长","子书","子桑","即墨","达奚","褚师"});

    /**
     * 电话号码脱敏 保留前3后四 如 184****6270
     *
     * @param phoneNumber
     * @return
     */
    public static String formatPhoneNumber(String phoneNumber) {
        if (StringUtils.isNotEmpty(phoneNumber)) {
            return phoneNumber.replaceAll("(?<=\\w{3})\\w(?=\\w{4})", "*");
        }

        return phoneNumber;
    }

    /**
     * 身份证号脱敏 保留前三后四, 适用于15位和18位身份证号 如 539***********171x
     *
     * @param idNumber
     * @return
     */
    public static String formatIdNumber(String idNumber) {
        if (StringUtils.isNotEmpty(idNumber)) {
            return idNumber.replaceAll("(?<=\\w{3})\\w(?=\\w{4})", "*");
        }
        return idNumber;
    }

    /**
     * 姓名脱敏
     * 两字:保留前一位,后一位脱敏 ,如 李明 -> 李*
     * 三字:保留前一前,后一位,中间脱敏 ,如 李世民 -> 李*民,欧阳锋 -> 欧阳*
     * 四字:保留前两位 ,后两位脱敏 ,如 欧阳平平 -> 欧阳**
     * 大于四字: 前2后2,其他脱敏
     * @param name
     * @return
     */
    public static String formatName(String name) {
        if (StringUtils.isNotEmpty(name)) {
            Integer len = name.length();
            switch (len) {
                case 2:
                    // todo 保留前一位,后一位脱敏 ,如 李明 -> 李*
                    return name.replaceAll("(?<=\\S{1})\\S", "*");
                case 3:
                    // todo 保留前一前,后一位,中间脱敏 ,如 李世民 -> 李*民
                    // todo 但是如果是 复姓 + 一个字 的话 ,如 欧阳锋 —> 欧*锋 ,正确的应该处理成 欧阳*
                    return compoundSurnames.contains(name.substring(0,2))?name.replaceAll("(?<=\\S{2})\\S", "*"):name.replaceAll("(?<=\\S{1})\\S(?=\\S{1})", "*");
                case 4:
                    // todo 保留前两位 ,后两位脱敏 ,如 欧阳平平 -> 欧阳**
                    return name.replaceAll("(?<=\\S{2})\\S", "*");
                default:
                    // todo 其他的默认保留前2后2,其他脱敏
                    return name.replaceAll("(?<=\\S{2})\\S(?=\\S{2})", "*");
            }
        }
        return name;
    }
}

方式2 更全面 https://mp.weixin.qq.com/s/uKlit0Cu8ZhqM_1I1_N-9Q

你可能感兴趣的:(java,java)