Cannot detect any meaningful timing difference in PHP (constant timing attack)

76 Views Asked by At

There's quite a few articles around PHP stating that constant timing attacks are possible when doing direct string comparisons. I've written some sample code to try and determine the order of magnitude difference but it's showing that it's not always the case that one is quicker than the other, even when doing millions of tests.

You would expect the first iteration active time to be quicker, as the first character is wrong in the string and thus the comparison can bail out, but it's not always the case.


$target = 'hello-world';
$comparison = ['Xello-world', 'hello-worlX'];

foreach($comparison as $x){
    $time = 0;
    $total = 500000;
    for($i = 0; $i < $total; $i++){
        $start = microtime(true);

        /** Actually perform the comparison */
        $result = ($target === $comparison);
        $end = microtime(true);

        /** Add up so we can compute the average **/
        $time += $end - $start;
    }

    echo "Duration for $x: " . ($time / $total) . PHP_EOL;
}
0

There are 0 best solutions below