java - 如何创建一个 Java 程序来检查您的密码是否安全?

标签 java passwords

我希望程序做两件事:

  1. 检查字符串(密码输入)是否同时包含字母和数字。
  2. 检查密码是否至少有 8 个字符。

这是我的代码:

import java.util.*;
class howstrong
{
  public static void main(String ar[])
  {
    String password;
    int i;
    int c=0;
    Scanner in = new Scanner(System.in);
    System.out.println("ENTER PASSWORD");
    password = in.next();
    if (password.length() <= 8)
    {
      for (i = 0; i <= password.length(); i++)
      {
        char x = password.charAt(i);
        if (Character.isLetter(x))
        {
          if (Character.isDigit(x))
          c = 1;
        }
      }
      if (c == 1)
        System.out.println("STRONG");
      else 
        System.out.println("NOT STRONG");
    }
    else
      System.out.println("HAVE AT LEAST 8 CHARACTERS");
  }
}

最佳答案

你有几个问题:

i <= password.length()应该是 i < password.length()

if (password.length() <= 8)应该是 if (password.length() >= 8)

您正在检查字符是否同时是字母和数字。

最后,我建议使用两个标志,一个检测是否有字母,另一个检测是否有数字。

把它们放在一起:

import java.util.Scanner;

class howstrong {
    public static void main(final String ar[]) {
        String password;
        Scanner in = new Scanner(System.in);
        System.out.println("ENTER PASSWORD");
        password = in.next();

        boolean hasLetter = false;
        boolean hasDigit = false;

        if (password.length() >= 8) {
            for (int i = 0; i < password.length(); i++) {
                char x = password.charAt(i);
                if (Character.isLetter(x)) {

                    hasLetter = true;
                }

                else if (Character.isDigit(x)) {

                    hasDigit = true;
                }

                // no need to check further, break the loop
                if(hasLetter && hasDigit){

                    break;
                }

            }
            if (hasLetter && hasDigit) {
                System.out.println("STRONG");
            } else {
                System.out.println("NOT STRONG");
            }
        } else {
            System.out.println("HAVE AT LEAST 8 CHARACTERS");
        }
    }
}

关于java - 如何创建一个 Java 程序来检查您的密码是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37454110/

相关文章:

java - 使用 javaagent 获取 tomcat 中托管的应用程序的开始和结束时间

java - 在 dynamodb 中查找列表字段包含值的所有项目

json - 在 post 请求正文中的 Json 对象中发送用户名和密码是否安全?

java - IO With Callback 设置数据库状态

java - 如何不生成maven jar

security - 密码符号,长度和 'strength'

Android 密码可见性切换不适用于支持库 25?

javascript - 密码确认不起作用

authentication - 如何将密码加密到 key 表文件中?

java.net.SocketException : Connection reset