暴力破解算法(Brute Force)

Brute Force算法,即暴力算法,是普通的模式匹配算法,Brute Force算法的思想就是将目标串S的第一个字符与模式串T的第一个字符进行匹配,若相等,则继续比较S的第二个字符和 T的第二个字符;若不相等,则比较S的第二个字符和T的第一个字符,依次比较下去,直到得出最后的匹配结果。Brute Force算法是一种蛮力算法。

 1 public delegate bool BruteForceCallback(ref char[] testChars);
 2 
 3         public static bool BruteForce(string testChars, int startLength, int endLength, BruteForceCallback bruteForceCallback)
 4         {
 5             for (int len = startLength; len <= endLength; ++len)
 6             {
 7                 char[] chars = new char[len];
 8 
 9                 for (int i = 0; i < len; ++i)
10                     chars[i] = testChars[0];
11 
12                 if (bruteForceCallback(ref chars))
13                     return true;
14 
15                 for (int i1 = len - 1; i1 > -1; --i1)
16                 {
17                     int i2 = 0;
18 
19                     for (i2 = testChars.IndexOf(chars[i1]) + 1; i2 < testChars.Length; ++i2)
20                     {
21                         chars[i1] = testChars[i2];
22 
23                         if (bruteForceCallback(ref chars))
24                             return true;
25 
26                         for (int i3 = i1 + 1; i3 < len; ++i3)
27                         {
28                             if (chars[i3] != testChars[testChars.Length - 1])
29                             {
30                                 i1 = len;
31                                 goto outerBreak;
32                             }
33                         }
34                     }
35 
36                 outerBreak:
37                     if (i2 == testChars.Length)
38                         chars[i1] = testChars[0];
39                 }
40             }
41 
42             return false;
43         }

 使用举例

 1             string dict = "abcde12345";
 2             string password = "a1b2c3d4";
 3 
 4 
 5             BruteForceCallback bruteForceCallback = delegate (ref char[] testChars)
 6             {
 7                 var str = new string(testChars);
 8                 return (str == password);
 9             };
10 
11 
12             bool result = BruteForce(dict, 1, password.Length, bruteForceCallback);

输出结果:

true
原文地址:https://www.cnblogs.com/88223100/p/brute-force-algorithm.html