问题
I have this homework assignment to make a recursive method to crack a password of a given length, n (unlimited and unknown!) made of small English letters, a-z ONLY.
Here's the class "Password" that creates a random password:
import java.util.Random;
public class Password {
private String _password = "";
public Password(int length) {
Random generator = new Random();
for (int i = 0; i < length; ++i) {
this._password = this._password + (char) (generator.nextInt(26) + 97);
}
}
public boolean isPassword(String st) {
return st.equals(this._password);
}
public String getPassword() {
return this._password;
}
}
And here is the question in detail:
"You must write a static recursive method,
public static String findPassword(Password p, int length)
that "cracks" the code.
Here's an example of a main method:
public class Main {
public static void main(String[] args) {
Password p = new Password(5);
System.out.println(p.getPassword());
System.out.println(Ex14.findPassword(p, 5));
}
}
Important notes:
- The method MUST be recursive, without using ANY loops.
- You may not use the getPassword method.
- If you would like to use a method of the String class, you may only use the following: charAt, substring, equals, length.
- You MAY use overloading, but you MAY NOT use other methods. (You cannot use String.replace/String.replaceall)
- You MAY NOT use static(global) variables.
- You MAY NOT use any Array. "
Here's what I have until now, which clearly doesn't work; :\
public static String findPassword(Password p, int length) {
return findPassword(p, length, "", 'a');
}
public static String findPassword(Password p, int length, String testPass, char charToChange) {
int currDig = testPass.length() - 1;
if (p.isPassword(testPass))
return testPass;
if (length == 0) // There is no password.
return ""; // Returns null and not 0 because 0 is a password.
if (length > testPass.length())
return findPassword(p, length, testPass + charToChange, charToChange);
if (testPass.length() == length) {
//TODO if charToChange is 'z', then make it the one before it '++', and reset everything else to a.
//if (charToChange == 'z') {
// charToChange = 'a';
// String newString = testPass.substring(0, currDig-1) +
// (charToChange++)
// +testPass.substring(currDig+1,testPass.length()-1);
System.out.println("it's z");
// TODO currDig --;
// String newerString = testPass.substring(0, currDig - 1)
// + (char) (testPass.charAt(testPass.length() - 1) - 25);
// currDig--;
}
return "";
}
Thank you very much! much appreciated! - TripleS
来源:https://stackoverflow.com/questions/37398621/backtracking-bruteforce-java-password-cracker