Search code examples
regexstringreplacesubstringmasking

Mask passwords in String


I have been wondering quite a bit on String functions such as replace().

My objective is simple. I have a logger, that logs strings into a text file, that contains passwords which needs to be masked before writing it to the log file.

For example:

str = "-field_value=userId=1,-field_value=password=pass123,-field_value=location=London,-field_value=day=Tuesday,-field_value=emailPassword=pass123,-field_value=fbPassword=pass1234";

Which approach would be the best in this case? The string may or may not end with any password "field_value".

I need to mask all the occurring "Passwords" with their exact length, in this string to get the following output:

str = "-field_value=userId=1,-field_value=password=*******,-field_value=location=London,-field_value=day=Tuesday,-field_value=emailPassword=*******,-field_value=fbPassword=********";

Which would be a more suitable option to use? Normal string handling (using substrings/replaceAll/indexOf) or StringBuilder functions?

Also, how effective is using Regular Expressions in this case? I've never used Regex extensively, so I have little idea on using it for this scenario.


Solution

  • I used String.replaceAll(regex, replace) method, to search for password or emailPassword etc and did the masking. Not sure, if that's the most ideal method to do the masking in this case.