我尝试创建一个C#应用程序,通过使用bruteforce恢复MD5哈希密码(仅用于测试,限制为小写a-z)
我遇到了循环问题。它需要在尝试a-z后添加一个新字符并启动一个尝试所有可能组合的新循环。
以下代码有效,但远非最佳。关于如何制作一个聪明的"循环?
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++;
}
}
}
}
答案 0 :(得分:1)
试试这个:
// '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';
}
}