Mask Sensitive Values In Log Strings

Mask card numbers, emails, and phone numbers with repeat and substring so logs keep the shape of a value without exposing the sensitive parts.

JavaSecurity Boundaries

Code

snippet
public class SecretMasker {

    // Masking sensitive values: keep only the last four digits of a card number, star out the rest
    static String maskPan(String pan) {
        if (pan.length() < 4) {
            return "*".repeat(pan.length());
        }
        return "*".repeat(pan.length() - 4) + pan.substring(pan.length() - 4);
    }

    // Emails keep the first character and the domain; the rest of the local part is masked
    static String maskEmail(String email) {
        int at = email.indexOf('@');
        if (at <= 0) {
            return "***";
        }
        return email.charAt(0) + "***" + email.substring(at);
    }

    public static void main(String[] args) {
        System.out.println(maskPan("4111111111111111"));
        System.out.println(maskPan("123"));
        System.out.println(maskEmail("[email protected]"));
        // Phone masking before log output: keep prefix and suffix, hide the middle four digits, and the log no longer carries full PII
        String phone = "13800138000";
        System.out.println(phone.substring(0, 3) + "****" + phone.substring(7));
    }
}

How it works

The working surface is the class SecretMasker and the functions maskPan, maskEmail and main — everything else is wiring.

Points of care

  • The only prerequisite is the language toolchain itself.

Applying it

Signature: static String maskPan(String pan)

main calls 2 helpers in sequence: maskPan and maskEmail.

Statements that matter

return "*".repeat(pan.length() - 4) + pan.substring(pan.length() - 4);
return email.charAt(0) + "***" + email.substring(at);
return "*".repeat(pan.length());

Interactive Tools for This Topic

FAQ

How do you run Mask Sensitive Values In Log Strings?
Just run the file; everything it needs ships with the runtime itself.