【发布时间】:2018-05-07 15:37:50
【问题描述】:
我编写了一个函数,它接收一个 MD5 哈希值,并通过排列字符串的所有可能组合来找到它的输入/原始值。根据 BIT_CHEETAH 对 SO 问题的回答:
...如果不尝试诸如暴力破解之类的资源密集型、不实用且不道德的操作,就无法解密 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