刘光辉
9 小时以前 06f314545ac3514d7ce28939920866ae8188d31c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package jnpf.util;
 
import java.util.regex.Pattern;
 
/**
 * Privacy masking utilities for values returned to clients.
 */
public final class PrivacyMaskUtil {
 
    private static final Pattern MOBILE_PHONE_PATTERN = Pattern.compile("^1\\d{10}$");
    private static final Pattern MASKED_MOBILE_PHONE_PATTERN = Pattern.compile("^1\\d{2}\\*{4}\\d{4}$");
 
    private PrivacyMaskUtil() {
    }
 
    /**
     * Masks a mainland China mobile phone number as 138****5678.
     * Non-empty values in an unexpected format are fully masked to avoid leaking private data.
     *
     * @param mobilePhone mobile phone number
     * @return masked mobile phone number
     */
    public static String maskMobilePhone(String mobilePhone) {
        if (mobilePhone == null || mobilePhone.trim().isEmpty()) {
            return mobilePhone;
        }
        if (MASKED_MOBILE_PHONE_PATTERN.matcher(mobilePhone).matches()) {
            return mobilePhone;
        }
        if (!MOBILE_PHONE_PATTERN.matcher(mobilePhone).matches()) {
            return "****";
        }
        return mobilePhone.substring(0, 3) + "****" + substringLastNumber(mobilePhone);
    }
 
    public static String substringLastNumber(String mobilePhone) {
        return substringLastNumber(mobilePhone, 4);
    }
 
    public static String substringLastNumber(String mobilePhone, int length) {
        if (mobilePhone == null) {
            return null;
        }
        if (length <= 0) {
            return mobilePhone;
        }
        return mobilePhone.substring(Math.max(0, mobilePhone.length() - length));
    }
}