Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

string

mask

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

like image 500
user3815000 Avatar asked Dec 02 '25 09:12

user3815000


1 Answers

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.

like image 73
rahimv Avatar answered Dec 03 '25 23:12

rahimv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!