Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# bruteforce md5 hashed string

I'm trying to create a C# application that recovers a MD5 hashed password by using bruteforce (just for testing, limited to lowercase a-z)

I'm having trouble with the loops. It needs to add a new character after trying a-z and start a new loop that tries all the possible combinations.

The code below works but is far from optimal. Any tips on how to make a "smart" loop?

public void CompareMD5()
{
    string outputMD5 = "";
    int chars = 1;
    int loop = 0;
    int i = 0;
    int ii = 0;
    while (!outputMD5.Equals(targetMD5))
    {
        if (chars == 1)
        {
            Console.WriteLine("trying " + charSet[i]);
            outputMD5 = GenerateMD5(charSet[i]);
            i++;
            if (i >= charSet.Length)
            {
                Console.WriteLine("\n" + "*** ADDING CHAR ***" + "\n");
                i = 0;
                chars++;
            }
        }

        if (chars == 2)
        {
            Console.WriteLine("trying " + charSet[i] + charSet[ii]);
            outputMD5 = GenerateMD5(charSet[i] + charSet[ii]);
            i++;
            if (i >= charSet.Length)
            {
                i = 0;
                ii++;
            }
            if (ii >= charSet.Length)
            {
                ii = 0;
                i++;
                loop++;
            }
            if (loop == 1)
            {
                Console.WriteLine("\n" + "*** ADDING CHAR ***" + "\n");
                i = 0;
                ii = 0;
                chars++;
            }
        }
    }
}
like image 236
user3212568 Avatar asked Mar 08 '26 16:03

user3212568


1 Answers

Try this one:

  // 'a', ..., 'z', 'aa', ..., 'zz', 'aaa', ..., 'zzz'
  int maxLength = 3;

  for (int length = 1; length <= maxLength; ++length) {
    // initial combination "a...a" ('a' length times)
    StringBuilder Sb = new StringBuilder(new String('a', length));

    while (true) {
      String value = Sb.ToString();
      //TODO: Test MD5 here
      // if (value.Equals(targetMD5)) {...}

      // Is this the last combination? (all 'z' string)
      if (value.All(item => item == 'z'))
        break;

      // Add one: aaa -> aab -> ... aaz -> aba -> ... -> zzz
      for (int i = length - 1; i >= 0; --i)
        if (Sb[i] != 'z') {
          Sb[i] = (Char) (Sb[i] + 1);

          break;
        }
        else
          Sb[i] = 'a';
    }
  }
like image 158
Dmitry Bychenko Avatar answered Mar 10 '26 15:03

Dmitry Bychenko