Regular Expression for Password Validation in Java – Java 中用于密码验证的正则表达式

最后修改: 2024年 1月 29日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.导言

Regarding cybersecurity, password validation is essential in protecting users’ accounts. Moreover, using regular expressions (regex) in Java provides a powerful and dynamic way of imposing specific standards for password complexity.

关于网络安全,密码验证对于保护用户的账户至关重要。此外,在 Java 中使用正则表达式(regex)提供了一种功能强大的动态方式,可对密码复杂性实施特定标准。

In this tutorial, we’ll delve into utilizing the regex for Java-based password validation processes.

在本教程中,我们将深入探讨如何利用 regex 进行基于 Java 的密码验证过程。

2. Criteria for a Robust Password

2.稳健密码的标准

Before we get into the code, we’ll establish what makes a strong password. An ideal password should:

在学习代码之前,我们先来了解一下怎样的密码才是强密码。一个理想的密码应该

  • Have eight characters or more
  • Include a capital letter
  • Use at least one lowercase letter
  • Consists of at least one digit
  • Need to have one special symbol (i.e., @, #, $, %, etc.)
  • Doesn’t contain space, tab, etc.

3. Implementation in Java

3.用 Java 实现

3.1. Regular Expression-based Password Validation

3.1.基于正则表达式的密码验证

Regular expressions, or regex, are useful tools in Java that allow searching, matching, and transforming strings based on certain patterns. In the same context, regex adopts a more static approach for password validation that operates with the help of predefined regular expressions.

正则表达式或 regex 是 Java 中的有用工具,可根据特定模式搜索、匹配和转换字符串。在同样的情况下,regex 采用了一种更静态的密码验证方法,借助预定义的正则表达式进行操作。

The following Java regular expression encapsulates the specified requirements:

下面的 Java 正则表达式封装了指定的要求:

^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@#$%^&+=]).{8,}$

Breaking down its components:

分解其组成部分:

  • ^: indicates the string’s beginning
  • (?=.*[a-z]): makes sure that there is at least one small letter
  • (?=.*[A-Z]): needs at least one capital letter
  • (?=.*\\d): requires at least one digit
  • (?=.*[@#$%^&+=]): provides a guarantee of at least one special symbol
  • .{8,20}: imposes the minimum length of 8 characters and the maximum length of 20 characters
  • $: terminates the string

Let’s use regex for password validation:

让我们使用 regex 验证密码:

@Test
public void givenStringPassword_whenUsingRegulaExpressions_thenCheckIfPasswordValid() {
    String regExpn = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])(?=\\S+$).{8,20}$";

    Pattern pattern = Pattern.compile(regExpn, Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(password);

    assertTrue(matcher.matches());
}

Here, we characterize the regExpn regular expression, which specifies certain rules for a password. Besides, we compile the regExpn regular expression into a pattern using Pattern.compile() method and then create a matcher for the given password through the pattern.matcher() method.

在此,我们将描述 regExpn 正则表达式的特征,该表达式指定了密码的某些规则。此外,我们使用 Pattern.compile() 方法将 regExpn 正则表达式编译成 Pattern ,然后通过pattern.matcher() 方法为给定的 password 创建 matcher

Lastly, we utilize the matcher.matches() method to determine if the password meets the regExpn regular expression.

最后,我们使用 matcher.matches() 方法来确定 password 是否符合 regExpn 正则表达式。

3.2. Dynamic Password Validation

3.2.动态密码验证

This approach presents a dynamic password verification method that enables the creation of a pattern based on different attributes. This technique involves an arbitrary pattern, including a minimum/maximum length, special symbols, and other elements.

这种方法提出了一种动态密码验证方法,可以根据不同的属性创建一个模式。这种技术涉及任意模式,包括最小/最大长度、特殊符号和其他元素。

Let’s implement this approach:

让我们采用这种方法:

@Test
public void givenStringPassword_whenUsingDynamicPasswordValidationRules_thenCheckIfPasswordValid() {
    boolean result = false;
    try {
        if (password != null) {
            String MIN_LENGTH = "8";
            String MAX_LENGTH = "20";
            boolean SPECIAL_CHAR_NEEDED = false;

            String ONE_DIGIT = "(?=.*[0-9])";
            String LOWER_CASE = "(?=.*[a-z])";
            String UPPER_CASE = "(?=.*[A-Z])";
            String SPECIAL_CHAR = SPECIAL_CHAR_NEEDED ? "(?=.*[@#$%^&+=])" : "";
            String NO_SPACE = "(?=\\S+$)";

            String MIN_MAX_CHAR = ".{" + MIN_LENGTH + "," + MAX_LENGTH + "}";
            String PATTERN = ONE_DIGIT + LOWER_CASE + UPPER_CASE + SPECIAL_CHAR + NO_SPACE + MIN_MAX_CHAR;

            assertTrue(password.matches(PATTERN));
        }

    } catch (Exception ex) {
        ex.printStackTrace();
        fail("Exception occurred: " + ex.getMessage());
    }
}

Here, we first ensure that the password doesn’t equal null before carrying on with validation. Then, the method determines validation criteria through individual strings, stipulating such issues as the presence of one digit, one lower case symbol, and an upper case letter with optionally special characters.

在这里,我们首先要确保密码不等于null,然后再进行验证。然后,该方法通过单个字符串确定验证标准,规定密码必须包含一个数字、一个小写符号和一个大写字母,并可选择包含特殊字符。

Moreover, we use the MIN_MAX_CHAR string to establish the password’s minimum and maximum length limits, using defined standards MIN_LENGTH and MAX_LENGTH. Afterward, the composite PATTERN string concatenates all the indicated prerequisites to develop a dynamic validation pattern.

此外,我们使用 MIN_MAX_CHAR 字符串来确定密码的最小和最大长度限制,使用的是定义的标准 MIN_LENGTHMAX_LENGTH随后,复合 PATTERN 字符串将所有指定的先决条件连接起来,形成动态验证模式。

Finally, we utilize the assertTrue(password.matches(PATTERN)) method to verify the password’s compliance with the dynamically created pattern. If exceptions occur during validation, the test is considered failed; details of the exception are printed for debugging purposes.

最后,我们使用 assertTrue(password.matches(PATTERN)) 方法来验证密码是否符合动态创建的模式。如果在验证过程中出现异常,测试将被视为失败;异常的详细信息将被打印出来,以便调试。

This approach provides the flexibility to set password validation rules by changing parameters, which makes it appropriate for different validators.

这种方法提供了通过更改参数来设置密码验证规则的灵活性,因此适用于不同的验证器。

4. Conclusion

4.结论

In summary, Java regular expressions are a reliable mechanism for performing text validation and manipulation, particularly when it involves the application of strong password security.

总之,Java 正则表达式是执行文本验证和操作的可靠机制,尤其是在涉及应用强密码安全性时。

Hence, in this article, we give a concise step-by-step guide for constructing an appropriate regular expression to validate passwords, providing the foundation for alteration that can increase safety during user account creation.

因此,在本文中,我们将提供一个简明的分步指南,指导如何构建一个合适的正则表达式来验证密码,为更改密码提供基础,从而提高用户账户创建过程中的安全性。

As always, the complete code samples for this article can be found over on GitHub.

与往常一样,本文的完整代码示例可在 GitHub 上找到