I have a brute force algorithm, but never fully understood it. I have a vague grasp of some of the things that go on, but every time I try to follow what happens exactly, I get lost (for example, the index variable is a little confusing). Any offers on how to make the algorithm more efficient are also welcome.
Note – I already have the algorithm, and it compiles and works. Please don’t accuse me of trying to use this for malicious intent, because I haven’t used it for that purpose, and I never plan to. I just want to know how it works.
public class BruteForceTest
{
public String username = new String();
public static String password = "ZZZZZ";
public static char[] charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
private static char[] currentGuess = new char[1];
public static void bruteForce()
{
String attempt = new String();
Date start = new Date();
while (true)
{
if (attempt.equals(password))
{
Date end = new Date();
System.out.println("Password: " + attempt + "\nTotal time to crack: " + ((end.getTime() - start.getTime()) / 1000) + " seconds." + "\n");
break;
}
attempt = in.toString();
// System.out.println("Tried: " + attempt);
in.increment();
}
}
public BruteForceTest()
{
Arrays.fill(currentGuess, charset[0]);
}
public void increment()
{
int index = currentGuess.length - 1;
while (index >= 0)
{
if (currentGuess[index] == charset[charset.length - 1])
{
if (index == 0)
{
currentGuess = new char[currentGuess.length + 1];
Arrays.fill(currentGuess, charset[0]);
break;
}
else
{
currentGuess[index] = charset[0];
index--;
}
}
else
{
currentGuess[index] = charset[Arrays.binarySearch(charset, currentGuess[index]) + 1];
break;
}
}
}
public String toString()
{
return String.valueOf(currentGuess);
}
}
Brute forcing is a heuristic technique that means, essentially, you’re going to try to analyze every possible scenario by taking advantage of how much faster a computer is than a human brain. For example, you’re not trying to deductively figure out the password or the next best move in a Chess game; you just test every possible situation and use the right one (or the best one according to some metric, depending on what the brute force algorithm is meant to accomplish).
Your code simply goes through all the possible values that could be held for a password and checks to see whether it has found it or not. If it doesn’t, it moves on to the next possible combination until it does.
It’s also a demonstration of a worst-case scenario, since the password, being defined as
ZZZZZ, will be the last thing the algorithm attempts as a solution (assuming the maximum password length is defined as five characters.)Also, as far as you being worried that people think you’re using this algorithm for malicious purposes, I wouldn’t be too concerned. Hardly any computer systems would actually be vulnerable to this kind of attack, and you would be locked out long before you ever actually happened upon a password.