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)); } }