Java蛮力密码破解程序

时间:2019-11-15 02:07:06

标签: java

我正在制作蛮力密码破解程序。我可以使用for循环查找与原始密码匹配的字符。但是输出的顺序不正确。输出按字母顺序排列。我该如何解决? 输出应该类似于“

z
ze
zeb
zebr
zebra

代码:

        public static void main(String[] args) {
    String password = "zebra";
    char [] passArr = new char [password.length()];
    passArr = password.toCharArray();

    String brutePass = "";
    char[] alphabet = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p','q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
    boolean solved = false;

    while (solved != true) {
        for (int i = 0; i < alphabet.length; i++) {
            for (int j = 0; j < passArr.length; j++) {
                if (alphabet[i] == passArr[j]) {
                    //brutePass +=passArr[j];
                    //System.out.println(brutePass);

                    StringBuilder forcedPass = new StringBuilder(brutePass);
                    forcedPass.insert(passArr[j], alphabet[i]);
                    System.out.println(forcedPass.toString());
                    solved = true;
                }
            }
        }
    }
}

}

2 个答案:

答案 0 :(得分:1)

根据所需的输出,代码应如下所示:

public static void main(String[] args) {
    String password = "zebra";
    char [] passArr = password.toCharArray();

    String brutePass = "";
    char[] alphabet = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p','q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
    boolean solved = false;
   StringBuilder forcedPass = new StringBuilder(brutePass); // Initialize StringBuilder outside.
    while (solved != true) {
         for (int j = 0; j < passArr.length; j++) { //Moved for loop outside.
        for (int i = 0; i < alphabet.length; i++) {

                if (alphabet[i] == passArr[j]) {
                    forcedPass.append(passArr[j]); // Used append instead of insert
                    System.out.println(forcedPass.toString());
                    solved = true;
                }
            }
        }
    }
}

在这里,我进行了两项更改,我切换了内部循环和外部循环的位置,并且您使用了insert()类的StringBuilder方法,这是不正确的。您必须使用它的append()方法。要了解有关StringBuilder方法的更多信息,请访问this

答案 1 :(得分:0)

将passArr循环移到外部。

public static void main(String[] args) {
    String password = "zebra";
    char[] passArr = new char[password.length()];
    passArr = password.toCharArray();

    StringBuilder forcedPass = new StringBuilder();
    char[] alphabet = new char[]{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
    boolean solved = false;

    while (solved != true) {
        for (int j = 0; j < passArr.length; j++) {
            for (int i = 0; i < alphabet.length; i++) {
                if (alphabet[i] == passArr[j]) {
                    forcedPass.append(alphabet[i]);
                    System.out.println(forcedPass.toString());
                    solved = true;
                }
            }
        }
    }
}