Mask a String Except Last 4 Chars in Java

When we want to mask a part of sensitive data, such as a card number, it is very necessary to have a method that can consider all the conditions and finally give a masked output. The following code snippet shows how to implement a simple data mask using basic Java commands.

package org.example;

import org.junit.jupiter.api.Assertions;

public class App {
    public static void main(String[] args) {
        Assertions.assertEquals("************3456", maskString("1234567890123456"));
        Assertions.assertEquals("789", maskString("789"));
        Assertions.assertEquals("", maskString("     "));
        Assertions.assertNull(maskString(null));
    }

    public static String maskString(String input){
        if(input == null) {
            return null;
        }
        input = input.trim();
        int maskLength = input.length() - 4;
        if (maskLength <= 0)
            return input;

        String masked = input.replaceFirst(String.format("\\d{%d}", maskLength), "*".repeat(maskLength));
        System.out.printf("card: %s, masked: %s%n", input, masked);
        return masked;
    }
}

Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *