Just an idea I had for a Java exercise. Cracking a password like "testing" takes at least 15 minutes, so obviously it's not as efficient as it can be. What are your thoughts? I also never worked with multithreading, so I can imagine I could be doing things better there.
public class AlgoTester implements Runnable {
private static final char[] possibleChars = { 'a', 'b', 'c', 'd', 'e', 'f', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
private static int[] arrayIndices;
private static String testPassword = "testing";
private static final int passwordLength = testPassword.length();
private static boolean foundPassword = false;
private final static int threadCount = 5;
private static String passwordFound = "";
public static void main(String[] args) {
arrayIndices = new int[passwordLength];
for (int i = 0; i < arrayIndices.length; i++) {
arrayIndices[i] = 0;
}
for (int i = 0; i < threadCount; i++) {
new Thread(new AlgoTester()).start();
}
}
private synchronized static boolean advanceIndicies() {
synchronized (arrayIndices) {
if (foundPassword)
return false;
int maxValue = possibleChars.length - 1;
for (int i = 0; i < passwordLength; i++) {
int inverse = arrayIndices.length - i - 1;
if (arrayIndices[inverse] == maxValue) {
if (inverse - 1 == -1)
return false;
arrayIndices[inverse] = 0;
continue;
} else {
arrayIndices[inverse] = arrayIndices[inverse] + 1;
return true;
}
}
return false;
}
}
private synchronized static String genPassword() {
synchronized (arrayIndices) {
StringBuilder builder = new StringBuilder();
for (int i : arrayIndices) {
builder.append(possibleChars[i]);
}
String returning = builder.toString();
System.out.println(Thread.currentThread().getName() + ": Checking: " + returning);
return returning;
}
}
private static boolean checkPassword() {
// TODO Auto-generated method stub
return (foundPassword = genPassword().equals(testPassword));
}
@Override
public void run() {
while (!foundPassword) {
if (checkPassword()) {
passwordFound = genPassword();
System.out.println("----------------------");
System.out.println("Found Password: " + passwordFound);
System.out.println("----------------------");
foundPassword = true;
}
if (!advanceIndicies()) {
return;
}
}
}
}