Reputation: 11
I am making a brute force password cracker. I am able to use for loops to find which characters match the original password. But the output is not in the correct order. the output is in alphabetical order. How do i fix this? the output should be something like"
z
ze
zeb
zebr
zebra
Code:
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;
}
}
}
}
}
}
Upvotes: 0
Views: 3940
Reputation: 943
Based on your required output, your code should look like this below:
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;
}
}
}
}
}
Here, I have made two changes, I swapped the position of your inner and outer loop and You have used insert()
method of StringBuilder
class, which is incorrect. You have to use the append()
method of it. To find out more about StringBuilder
methods,visit this.
Upvotes: 1
Reputation: 295
Move the passArr loop outside.
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;
}
}
}
}
}
Upvotes: 0