Skip to content

Instantly share code, notes, and snippets.

@dunglas
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dunglas/4b33d449fd1b05469077 to your computer and use it in GitHub Desktop.
Save dunglas/4b33d449fd1b05469077 to your computer and use it in GitHub Desktop.
hash_equals benchmark
<?php
/**
* Constant-time comparision length leak benchmark.
* Inspirated by https://gist.github.com/yohgaki/ede544f290c6cf9fa90d
*
* @author Kévin Dunglas
*/
$knownSize = 1024;
$userShortSize = 512;
$userLongSize = 2048;
$iterations = 1000;
$i = 0;
while ($i < 10) {
$known = file_get_contents('/dev/urandom', 0, NULL, -1, $knownSize);
$userShort = file_get_contents('/dev/urandom', 0, NULL, -1, $userShortSize);
$userLong = file_get_contents('/dev/urandom', 0, NULL, -1, $userLongSize);
benchmark($known, $knownSize, $userShort, $userShortSize, $iterations);
benchmark($known, $knownSize, $known, $knownSize, $iterations);
benchmark($known, $knownSize, $userLong, $userLongSize, $iterations);
$i++;
}
function benchmark($known, $knownSize, $user, $userSize, $iterations) {
$n = 0;
$start = microtime(TRUE);
while($n < $iterations) {
hash_equals($known, $user);
$n++;
}
$end = microtime(TRUE) - $start;
printf('User size: %d Known size: %d Elapsed: %f Iterations: %d'.PHP_EOL, $userSize, $knownSize, $end, $iterations);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment