【问题标题】:How to decrease runtime for generating permutations of a string?如何减少生成字符串排列的运行时间?
【发布时间】:2018-05-07 15:37:50
【问题描述】:

我编写了一个函数,它接收一个 MD5 哈希值,并通过排列字符串的所有可能组合来找到它的输入/原始值。根据 BIT_CHEETAH 对 SO 问题的回答:

...如果不尝试诸如暴力破解之类的资源密集型、不实用且不道德的操作,就无法解密 MD5。

(来源:encrypt and decrypt md5

我很清楚这一点,但是,我正在使用这个场景来实现一个字符串置换函数。我也想坚持使用递归方法而不是其他方法。 Mark Byers 的帖子可能总结了这样做的最佳总结:

 - Try each of the letters in turn as the first letter and then find all
   the permutations of the remaining letters using a recursive call.
 - The base case is when the input is an empty string the only permutation is the empty string.

(Generating all permutations of a given string)

无论如何,所以我实现了这个并得到了以下结果:

function matchMD5($possibleChars, $md5, $concat, $length) {
    for($i = 0; $i < strlen($possibleChars); $i++) {
        $ch = $possibleChars[$i];
        $concatSubstr = $concat.$ch;
        if(strlen($concatSubstr) != $length) {
            matchMD5($possibleChars, $md5, $concatSubstr, $length);
        }
        else if(strlen($concatSubstr) == $length) {
            $tryHash = hash('md5', $concatSubstr);
            if ($tryHash == $md5) {
                echo "Match! $concatSubstr ";
                return $concatSubstr;
            }
        }
    }
}

100% 有效,但是当我传入一个四字符数组时,我的服务器会运行 10.7 秒来生成匹配项,其中匹配项大约是所有可能排列的 1/10。我的函数置换的有效字符(称为 $possibleChars)包含所有字母数字字符以及一些选定的标点符号:

0123456789.,;:abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ

问题:上面的代码能否写得更快?

【问题讨论】:

标签: php algorithm recursion encryption


【解决方案1】:

在进行暴力破解时,您必须遍历所有可能性,那里没有偷工减料的方法。因此,您只能对代码进行分析,以找出应用程序花费最多时间在做什么,然后尝试对其进行优化。

【讨论】:

  • 他似乎明白什么是蛮力。它认为问题在于生成排列的速度
猜你喜欢
  • 2022-06-29
  • 2015-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-04
  • 2017-07-10
  • 1970-01-01
相关资源
最近更新 更多