Search code examples
javaspringspring-bootlogback

Springboot-Logback: Mask SSN last four Digits


I am trying to mask sensitive information like SSN and Credit card in my Spring boot application using Logback.xml. I searched various links in web, but could not find good solution.Is there a simple-way or any library to mask the sensitive information in logs?

Input

{"firstName":"John","lastName":"Doe","SSN":123456789}

output:

  {"firstName":"John","lastName":"Doe","SSN":12345****}

And found this on stack overflow but trouble figuring out regex.Any help would be greatly appreciated

Mask sensitive data in logs with logback


Solution

  • You could try using String.ReplaceAll(String regex, String replacement). The regex would want to just match the first 5 digits of the SSN, keep them, and replace everything else. Since we know that every SSN is only 9 digits, just capture the first 5 like so:

    String rgx = "([0-9]{5})[0-9]*";
    

    We capture the first 5 in a group, we can then reference that group in ReplaceAll() with $1. We don't care how many digits are after it, so just use [0-9]* to match the rest. After we reference the first 5 digits with $1, just replace everything else with ****.

    The result:

    String baseSSN = "123456789";    
    String rgx = "([0-9]{5})[0-9]*";
    String modifiedSSN = baseSSN.ReplaceAll(rgx, "$1****"); //modifiedSSN = 12345****
    

    You can mess with the regex here.