【问题标题】:Java Mask Passwords in String字符串中的 Java 掩码密码
【发布时间】:2022-01-19 11:10:37
【问题描述】:

我正在寻找一种优雅的方式来屏蔽字符串中的密码。我的问题是,找到它们的正则表达式还包含不需要屏蔽的内容,并且正则表达式本身应该可由高级用户维护。

List<String> regexes = List.of("password = (.*)", "pw = (.*)");
regexs.forEach(r -> maskThePw(str, r, "*");
String maskThePw(String str, String regex, String replace){
    return str.replaceAll(regex, replace)
}

现在这甚至可以与 String.replaceAll 一起使用吗?我尝试将 ""password" : "(.*)"" 作为正则表达式,但这要求我将替换中的第一部分 (password : ) 作为常量。

我尝试将开头分组:

requestStr.replaceAll("(\"password\" : \")(.*)\"", "$1*****")

这可行 - 在某种程度上,但需要组的数量保持不变,因为我希望模式是可变的。在这种情况下。我需要知道 $2 是密码,$1 是之前的密码。

我错过了什么吗?我想搜索某个字符串并将组 $1 替换为与它包含的相同数量的星号。如果不可能,也可以使用固定数量的星号(如我的示例所示)。

想要的输出是:

Input:
password = "test", username = "test"

Output:
password = "****", username = "test"

但也适用于其他情况:

Input:
secret = "test", username = "test"

Output:
secret = "****", username = "test"

而必须可以动态添加触发屏蔽的新模式。比如“key”、“hidden”之类的。

谢谢!

【问题讨论】:

  • 当您声明时您到底想解决什么问题:This works - to some degree but requires the amount of groups to be constant.
  • 您可能想重新访问minimal reproducible example
  • 为什么需要组? replaceAll("\"password\" : \".*\"", "\"password\": *****") 做同样的工作。
  • 显示哈希是否重要?
  • 如果有人在密码中使用双引号 ("),您希望您的代码做什么?

标签: java regex passwords


【解决方案1】:

所以我同时自己解决了:

但是,请始终欢迎提出使其更优雅或更高效的建议。

private String mask(final String str)
{
    String newStr = str;
    final String[] masks = getConfiguration()
        .getString(LOG_MASK_REGEX).split(SEMICOLON);
    final String maskCharacter = getConfiguration()
        .getString(LOG_MASK_CHARACTER, ASTERISK);
    for (final String mask : masks)
    {
        final Pattern pattern = Pattern.compile(mask, Pattern.DOTALL);
        final Matcher matcher = pattern.matcher(newStr);
        if (matcher.matches())
        {
            final String found = matcher.group(1);
            newStr = newStr.replace(found, StringUtils.repeat(maskCharacter, found.length()));
        }
    }
    return newStr;
}

这些是属性中配置的正则表达式:

log.mask.regex = .*"password" : "(.*?)".*;.*"username" : "(.*?)".*;.*"email" : "(.*?)".*

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-29
    • 1970-01-01
    • 1970-01-01
    • 2017-11-04
    • 2015-02-23
    • 2020-07-08
    • 2012-12-12
    • 1970-01-01
    相关资源
    最近更新 更多