user3024119 user3024119 - 6 months ago 104
Java Question

Java Regular Expression to mask sensitive data in logs

"PUT /v1/users/me/change_password.json?api_key=pDY0VK7YFv9btw6pasXZ&current_password=Qwerty123&password=Qwerty1234&password_confirmation=Qwerty1234 HTTP/1.1" 200 -


I need regular expression which replace
password
,
current_password
and
password_confirmation
values with text Filtered.

Required Output

"PUT /v1/users/me/change_password.json?api_key=pDY0VK7YFv9btw6pasXZ&current_password=[FILTERED]&password=[FILTERED]&password_confirmation=[FILTERED] HTTP/1.1" 200 -

Answer

I got the solution. I created a enum. public enum MaskSensitiveData {

CURRENT_PASSWORD("(current[_\\s-]password)[=:\"\\s]*(\\w*)"),

PASSWORD("[&,;\"\'\\s]+(password|pwd)[=:\"\\s]*(\\w*)"),

PASSWORD_CONFIRMATION("(password[_\\s-]confirmation)[=:\"\\s]*(\\w*)"),

API_KEY("(api[_\\s-]key)[=:\"\\s]*(\\w*)"),

RESET_PASSWORD_TOKEN("(reset[_\\s-]password[_\\s-]token)[=:\"\\s]*(\\w*)"),

UPLOAD_TOKEN("(upload[_\\s-]token)[=:\"\\s]*(\\w*)"),

AUTH_TOKEN("(auth[_\\s-]token)[=:\"\\s]*(\\w*)");

private String regEx;

 MaskSensitiveData(String exp) {
    regEx = exp;
}


public String getRegEx() {
    return regEx;
}

}

  String message = event.getRenderedMessage();
        StringBuffer sb = new StringBuffer(message);
        for (MaskSensitiveData sensitiveData : MaskSensitiveData.values()) {

            Pattern PATTERNCARD =
                    Pattern.compile(sensitiveData.getRegEx(), Pattern.CASE_INSENSITIVE);
            Matcher matcher = PATTERNCARD.matcher(message);

            if (matcher.find()) {
                String maskedMessage = matcher.group(2);
                message = message.replaceFirst(maskedMessage, MASKCARD);