I'm trying to create a C# brute force MD5 password checker. If I run it with "test1" without MD5, it completes in 15 seconds. I would like to make it faster, but I'm a c# beginner, and don't know how to optimize code anymore.
Basically, instead of nested for
loops, if
using flags (of type boolean), so if you have 4 char long pass it goes like this:
_ _ _ _ -> try every letter and number at last place, then set last flag on true. If last flag == true then increment counter for third place.
private string bruteForce(int lenght)
{
MD5 md55 = System.Security.Cryptography.MD5.Create();
char[] words =
{
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'r', 'q', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','R','Q','S','T','U','V','W','X','Y','Z',
'0','1','2','3','4','5','6','7','8','9'
};
bool[] konec = new bool[lenght];
int flag = lenght;
char[] pass = new char[flag];
int[] signal = new int[lenght];
for (int j = 0; j < lenght; j++)
{
signal[j] = -1;
konec[j] = false;
}
flag--;
string tmp = "";
bool over=false;
while (!over)
{
for (int k = 0; k < lenght; k++)
{
if (konec[k])
{
if (k == 0) return "not found";
int t = ++signal[k - 1];
if (t == words.Length - 1) {konec[k - 1] = true;
signal[k - 1] = 0;
break;
}
pass[k - 1] = words[t];
konec[k] = false;
}
}
for (int i = 0; i < words.Length; i++)
{
if (!konec[flag])
{
pass[flag] = words[i];
tmp = new string(pass);
byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(tmp);
byte[] hash = md55.ComputeHash(inputBytes);
// step 2, convert byte array to hex string
string emde= BitConverter.ToString(hash).Replace("-", "");
emde = emde.ToLower();
if (tmp == target)
{
MessageBox.Show(tmp + " " + target);
over = true;
break;
}
}
}
konec[flag] = true;
}
return tmp;
}
This is call on button click:
private void Button_Click(object sender, RoutedEventArgs e)
{
int l = Convert.ToInt32(stevilo.Text);
// lenght = 1;
// string a = "";
if (md5)
{
if (brute)
{
Stopwatch time = new Stopwatch();
time.Start();
target = zgoscevalna.Text;
for (int i = 1; i < l+1; i++)
{
int _i = i;
Thread t = new Thread(() =>
{
string a = bruteForce(_i);
if (a != "not found")
{
Dispatcher.Invoke(() =>
{
password.Text = a;
tajm.Text = (time.Elapsed.TotalSeconds).ToString();
});
Thread.CurrentThread.Abort();
}
else
{
Thread.CurrentThread.Abort();
}
});
t.Start();
}
}
else
{
}
}
private void
should line up withprivate
. \$\endgroup\$