Java Regular Expression用于屏蔽日志中的敏感数据

时间:2016-05-24 05:44:27

标签: java

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

我需要正则表达式,用文本Filtered替换passwordcurrent_passwordpassword_confirmation值。

必需的输出

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

1 个答案:

答案 0 :(得分:0)

我得到了解决方案。我创建了一个枚举。

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);