美文网首页
JAVA 数据脱敏

JAVA 数据脱敏

作者: zt_sole | 来源:发表于2021-09-01 16:40 被阅读0次
    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;
        }
    }
    

    相关文章

      网友评论

          本文标题:JAVA 数据脱敏

          本文链接:https://www.haomeiwen.com/subject/lhzxwltx.html