Java简单的脱敏方法

1、实现类

/*
 * Copyright (c) 2005, 2018, EVECOM Technology Co.,Ltd. All rights reserved.
 * EVECOM PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 */
package net.evecom.core.util;

/**
 * Created by Administrator on 2018/4/24.
 *
 * @author Harley Hong
 * @created 2018 /04/24 16:35:30
 */
public class DataConcealUtil {

    /**
     * The constant SIZE.
     */
    private static final int SIZE = 6;
    /**
     * The constant SYMBOL.
     */
    private static final String SYMBOL = "*";

    /**
     * 描述 create.
     *
     * @param value the value
     * @return the string
     * @author Harley Hong
     * @created 2018 /04/24 16:35:56 To conceal string.
     */
    public static String toConceal(String value) {
        if (null == value || "".equals(value)) {
            return value;
        }
        int len = value.length();
        int pamaone = len / 2;
        int pamatwo = pamaone - 1;
        int pamathree = len % 2;
        StringBuilder stringBuilder = new StringBuilder();
        if (len <= 2) {
            if (pamathree == 1) {
                return SYMBOL;
            }
            stringBuilder.append(SYMBOL);
            stringBuilder.append(value.charAt(len - 1));
        } else {
            if (pamatwo <= 0) {
                stringBuilder.append(value.substring(0, 1));
                stringBuilder.append(SYMBOL);
                stringBuilder.append(value.substring(len - 1, len));

            } else if (pamatwo >= SIZE / 2 && SIZE + 1 != len) {
                int pamafive = (len - SIZE) / 2;
                stringBuilder.append(value.substring(0, pamafive));
                for (int i = 0; i < SIZE; i++) {
                    stringBuilder.append(SYMBOL);
                }
                if ((pamathree == 0 && SIZE / 2 == 0) || (pamathree != 0 && SIZE % 2 != 0)) {
                    stringBuilder.append(value.substring(len - pamafive, len));
                } else {
                    stringBuilder.append(value.substring(len - (pamafive + 1), len));
                }
            } else {
                int pamafour = len - 2;
                stringBuilder.append(value.substring(0, 1));
                for (int i = 0; i < pamafour; i++) {
                    stringBuilder.append(SYMBOL);
                }
                stringBuilder.append(value.substring(len - 1, len));
            }
        }
        return stringBuilder.toString();
    }
}

2、结果演示

你好吗? -> 你**?
12345 -> 1***5

参考地址:https://wenku.baidu.com/view/895d7384ad51f01dc281f19c.html

猜你喜欢

转载自my.oschina.net/HarleyZhuge/blog/1800474