我昨天在python中对这个函数进行了原型设计,以强制执行md5哈希,它的工作非常精彩。
在这种情况下,它会打印Match: aa
和4124bc0a9335c27f086f24ba207a4912
。因为这是字符串“aa”的哈希值。
import hashlib
def crack(chars, st, hsh):
if chars == 0:
if hashlib.md5(st).hexdigest() == hsh:
print "Match: " + st
print hashlib.md5(st).hexdigest()
else:
for i in range(32,127):
new = st + str(unichr(i))
crack(chars - 1, new, hsh)
crack(2, "", "4124bc0a9335c27f086f24ba207a4912")
现在我正在尝试在javascript中实现它。我已经在使用md5库了,它工作正常。这是我写的代码,递归没有按预期工作。我将展示代码和控制台输出来说明。
<!DOCTYPE html>
<html lang="en">
<body>
<script src="js/md5.min.js"></script>
<script>
function crack(chars, st, hsh){
console.log(chars);
console.log(st);
if (chars == 0){
if (md5(st) == hsh){
console.log(st);
}
}
else {
for (i = 32; i <= 126; i++){
newst = st + String.fromCharCode(i);
crack(chars - 1, newst, hsh);
}
}
}
crack(2, "", "4124bc0a9335c27f086f24ba207a4912");
</script>
</body>
</html>
现在控制台输出:
2
(space ascii 32)
1
(space ascii 32)
0
(space ascii 32)
0
!
0
"
0
#
0
$
0
%
0
&
0
etc.
0
~ (ascii 126)
需要什么样的巫术来解决这个问题?
答案 0 :(得分:3)
你的循环迭代器i
是一个全局变量。将其设为var
或let
:
function crack(chars, st, hsh) {
if (chars == 0) {
if (md5(st) == hsh) {
console.log(st);
}
} else {
for (var i = 32; i <= 126; i++) { // <--- Declare i with var or let
var newst = st + String.fromCharCode(i);
crack(chars - 1, newst, hsh);
}
}
}
crack(2, "", "4124bc0a9335c27f086f24ba207a4912");
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/blueimp-md5/2.3.0/js/md5.min.js"></script>
&#13;
在递归函数调用中递增全局迭代器变量i
也会增加调用者的值。