user3815000 user3815000 - 1 year ago 168
Java Question

Mask part of the String data which is of different lengths using Java

I am in need to mask PII data for my application. The PII data will be of String format and of variable lengths, as it may include name, address, mail id's etc.

So i need to mask these data before logging them, it should not be a full mask instead, if the length of string is less than or equal to 8 characters then mask the first half with "XXX etc.."

If the length is more than 8 then mask the first and last portion of the string such that only the mid 5 characters are visible.
I know we can do this using java sub-stringa nd iterating over the string, but want to know if there is any other simple solution to address this.
Thanks in advance

Answer Source

If you are using Apache Commons, you can do like

String maskChar = "*";

//number of characters to be masked
String maskString = StringUtils.repeat( maskChar, 4);

//string to be masked
String str = "FirstName";

//this will mask first 4 characters of the string
System.out.println( StringUtils.overlay(str, maskString, 0, 4) );

You can check the string length before generating maskString using if else statement.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download