Skip to content
Advertisement

Why can’t I use a function to simplify my “for loops”

I build a webpage to crack simple MD5 hash of a four digit pin for fun. The method I used was basically try all combination and check against the MD5 value the user has entered. Below is the PHP code I created to accomplish the goal.

Debug Output:

<?php
$answer = "PIN not found";
if (isset($_GET['md5'])) {
  $txt = 'abcdefjhig';
  $time_pre = microtime(TRUE);
  $value = $_GET['md5'];
  $show = 15;

  for ($i = 0; $i <= 9; $i++) {
    $first = $i;
    for ($j = 0; $j <= 9; $j++) {
      $second = $j;
      for ($k = 0; $k <= 9; $k++) {
        $third = $k;
        for ($x = 0; $x <= 9; $x++) {
          $fourth = $x;
          $whole = $first . $second . $third . $fourth;
          $check = hash('md5', $whole);
          if ($check == $value) {
            $answer = $whole;
            echo "The pin is $answer";
          }
          if ($show > 0) {
            print"$check $whole n";
            $show = $show - 1;
          }
        }
      }
    }
  }
  echo "n";
  $time_post = microtime(TRUE);
  print "Elapsed time:";
  print $time_post - $time_pre;
}
?>

Notice that in the middle there are four very similar for loops,I tried to simplify this by using functions, but it just returns one four digit number which is 9999 instead of all of them. Below is the function I created:

function construct($input){
  for($i=0; $i<=9, $i++){
    $input=$i;
  } 
  return $input
}

Then I tried to call this function for four times to form all of the four digit numbers but it just gives me 9999. Can anybody help? Thanks a lot.

Advertisement

Answer

Try this:

for ($i=0; $i<=9999 ; $i++) { 
   $whole = sprintf('%04d', $i);
    $check=hash('md5', $whole);
    if($check==$value){
        $answer=$whole;
        echo "The pin is $answer";
        break; //remove this if you do not want to break the loop here
    }
    if ($show>0) {
        print"$check $whole n";
        $show=$show-1;          
    }   
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement