如何迭代生成字母和数字的所有可能组合以匹配可变长度字符串?

时间:2017-08-10 18:27:48

标签: c algorithm brute-force

我希望编写一个迭代逻辑程序,其中有一个输入字符串,程序从长度1开始,并尝试所有可能的字母和数字组合。如果未找到匹配项,它会尝试长度为2的所有可能的字母和数字组合,依此类推,直到找到与输入字符串匹配的内容。

例如,

string input = "xG7a";
// loop all possible combinations for length 1, i.e., 0-9 then A-Z, then a - z
// check for all if matches the input string
// loop all possible combinations for length 2, i.e., 00-09, then 0A-0Z, then 0a - 0z. Then 
// for 10-19, then 1A-1Z, then 1a - 1z ... till z0-z9, then zA-zZ, then za - zz
// again check for all if matches the input string
// Keep doing this for lengths 3, 4, 5 and so on till it matches with the input string.
// exit with status success if match else keep going till infinity
// This example would exit at length 4 when it matches with "xG7a"

这里匹配的所有可能组合的数量是(10 + 26 + 26 = 62)= 62 ^ 1 + 62 ^ 2 + 62 ^ 3 + ......直到匹配为止。

修改 更多细节:

  • 这是编写强制逻辑的练习的一部分
  • 预先不知道输入字符串。以上示例仅供参考。我已经弄明白了剩下的逻辑。生成的字符串将传递到哈希函数,该哈希函数生成与数据库中的密码哈希匹配的哈希。因此,要生成的字符串的动态性质。
  • 事先知道密码字符串只包含数字和大小写字母。

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

以正确的顺序创建一个包含所有可能字符的字符串:

 char charlist[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

然后,对于要检查的每个字符,循环遍历此字符串构建测试字符串并进行比较:

int i, found;
char str_to_test[5];
for (i=0, found=0; !found && i<strlen(charlist); i++) {
    str_to_test[0] = charlist[i];
    str_to_test[1] = 0;
    if (!strcmp(str_to_test, target_string)) {
        found = 1;
    }
}
if (found) {
    printf("found it!\n");
} else {
    printf("not found\n");
}

在每个子字符串的嵌套循环中重复。