Last active
January 1, 2016 04:49
-
-
Save Ocramius/8094168 to your computer and use it in GitHub Desktop.
Timing Attack simulation - just a very simple dummy to help understanding timing attacks. https://twitter.com/Ocramius/status/415055831608991744
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require_once __DIR__ . '/HashCracker.php'; | |
$password = 'hello'; | |
$hashed = md5($password); | |
var_dump('Hash to match: ' . $hashed); | |
$cracked = (new HashCracker())->runBenchmark($hashed); | |
var_dump('Cracked hash: ' . $cracked); | |
var_dump($cracked === $hashed ? 'Success!' : 'Fail :( Retry!'); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require_once __DIR__ . '/stupidStringComparison.php'; | |
class HashCracker | |
{ | |
private $range = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']; | |
private $length = 32; | |
private $cycles = 1000; | |
public function runBenchmark($hash, $prefix = '') | |
{ | |
foreach ($this->range as $key) { | |
$match = $prefix . $key; | |
$timers[$match] = microtime(true); | |
for ($i = 0; $i < $this->cycles; $i += 1) { | |
// this is where you bomb the server | |
stupidStringComparison($hash, $match); | |
} | |
$timers[$match] = microtime(true) - $timers[$match]; | |
} | |
asort($timers); | |
end($timers); | |
$hit = key($timers); | |
var_dump($hit); | |
if (strlen($hit) >= $this->length) { | |
return $hit; | |
} | |
return $this->runBenchmark($hash, $hit); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function stupidStringComparison($str1, $str2) | |
{ | |
for ($i = 0; $i < strlen($str2) && $i < strlen($str1); $i += 1) { | |
if ($str1[$i] !== $str2[$i]) { | |
return false; | |
} | |
usleep(10); // yes, I can't get something reliable with my box otherwise because of cpu spikes | |
} | |
// really stupid - ignore this part. Just made up to inflate times | |
return strlen($str1) === strlen($str2); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment