Here is an interesting script I wrote. It demonstrates how pcntl_fork() might be used as a useful tool.
<?php
/* This script serves the purpose of testing an algorithm designed to:
a.) Compare password hashes, or try passwords efficiently where the time to try a single password is 10 seconds.
b.) Spawn threads to work simultaneously on comparing hashes.
c.) Restrict the number of threads open at a time.
*/
//checks for divisibility
function divby($num,$den) {
$result = $num/$den;
$result2 = floor($result);
if ($result == $result2) {
return true;
}
else {
return false;
}
}
//checks whether a period of time fits into 2 second intervals occuring every 10 seconds. Interval may increase or decrease in size to use more or less memory.
function goodTime($elapsed) {
$num = floor($elapsed);
$num = $num/12;
$min = floor($num);
$min = 12*$min;
$max = $min+2;
if ($elapsed >= $min && $elapsed <= $max) {
return "yes";
}
else {
return "no";
}
}
$x = 30; //number of child threads
$pid = 1; //needed to create first thread
$xpass = md5('29');//hash to crack
$time = time();
$i = 1;
//parent spawns $x children.
while ($i <= $x) {
if (file_exists('childcall.txt')) {
unlink('childcall.txt');
exit;
}
$elapsed = time()-$time;
//children are only spawned during intervals occuring every 10 seconds leaving enough time for the previous batch of children to finish their task.
if (goodTime($elapsed)=="yes") {
//Are we the parent?
if ($pid != 0) {
//Give birth to a child.
$pid = pcntl_fork();
//create a record of how many children have been birthed.
$arr[$i] = $i;
$time2 = $elapsed;
}
//escort children out of the loop.
if ($pid == 0) {
$i = $x+1;
}
$i++;
}
}
//parent waits for children to finish playing.
if ($pid) {
$value = 1;
while (!file_exists('childcall.txt')) {
//wait
}
unlink('childcall.txt');
$time = time()+2;
while (time()<$time) {
//wait
}
exit;
}
//children take turns finding the highest array value, and changing it to 0
rsort($arr);
$value = max($arr);
$arr[$value] = 0;
$time = time()+10;
//simulate delay
while (time() < $time) {
//wait
}
//compare the high array value hash to the hash we are looking to crack.
if (md5($value) == $xpass) {
echo "$value \n";
}
if ($value == $x || md5($value) == $xpass) {
$file = "childcall.txt";
$content = true;
file_put_contents($file,$contents);
}
?>