Java Swing 注册表密码漏洞条件

Java Swing Register Form Password Weakness Conditions

我想在java做一个注册系统。它的进展非常顺利。我只有一个具体问题。密码弱点。我做到了,密码必须超过 8 个字符,简单

if(password.getText().length() > 8) { error message }

我也放了一个条件:

if(... < 8 || !(password.getText().contains("1"))) { error message }

但是在这种情况下,它只接受密码,如果你的密码例如:asdfghjk1 所以我尝试了很多||的条件像 !....contains("2")..|| 这样的条件!.包含(“9”)

但在这些条件下,它仅在密码为:123456789 时有效 但我真正想要做的是一个密码,长度超过 8 个字符,至少包含一个大写字母和至少一个数字。那有什么办法吗? 顺便说一下我用的是Java swing.

您可以使用正则表达式来做到这一点,但我不知道怎么做。 但这应该有效:

这是您验证密码的地方: 字符串密码String = password.getText();

if (passwordString.Length() > 8 && checkCapital(passwordString) && checkDigit(passwordString)){ valid password }

else { error message }

这是 checkCapital 我用的是 ascii 码:

private static boolean checkCapital(String string) {
    for (char c : string.toCharArray()) {
        int code = (int) c;
        if (code >= 65 && code <= 90) 
            return true;
    }
    return false;
}

这是校验位:

private static boolean checkDigit(String string) {
    for (int i = 0; i < 10; i++) {
        if (string.contains("" + i))
            return true;
    }
    return false;
}

解决这个问题的最好方法是使用正则表达式。在这里我给大家举例说明如何使用正则表达式来检查密码。

import java.util.regex.*; 
class GFG { 
  
    // Function to validate the password. 
    public static boolean
    isValidPassword(String password) 
    { 
  
        // Regex to check valid password. 
        String regex = "^(?=.*[0-9])"
                       + "(?=.*[a-z])(?=.*[A-Z])"
                       + "(?=.*[@#$%^&+=])"
                       + "(?=\S+$).{8,20}$"; 
  
        // Compile the ReGex 
        Pattern p = Pattern.compile(regex); 
  
        // If the password is empty 
        // return false 
        if (password == null) { 
            return false; 
        } 
  
        // Pattern class contains matcher() method 
        // to find matching between given password 
        // and regular expression. 
        Matcher m = p.matcher(password); 
  
        // Return if the password 
        // matched the ReGex 
        return m.matches(); 
    } 
  
    // Driver Code. 
    public static void main(String args[]) 
    { 
  
        // Test Case 1: 
        String str1 = "Thuans@portal20"; 
        System.out.println(isValidPassword(str1)); 
  
        // Test Case 2: 
        String str2 = "DaoMinhThuan"; 
        System.out.println(isValidPassword(str2)); 
  
        // Test Case 3: 
        String str3 = "Thuan@ portal9"; 
        System.out.println(isValidPassword(str3)); 
  
        // Test Case 4: 
        String str4 = "1234"; 
        System.out.println(isValidPassword(str4)); 
  
        // Test Case 5: 
        String str5 = "Gfg@20"; 
        System.out.println(isValidPassword(str5)); 
  
        // Test Case 6: 
        String str6 = "thuan@portal20"; 
        System.out.println(isValidPassword(str6)); 
    } 
} 

输出: 真的 错误的 错误的 错误的 错误的 假

您也可以通过关注下面的link来参考类似的主题:

Regex Java for password