Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions src/Compat.php
Original file line number Diff line number Diff line change
Expand Up @@ -2684,6 +2684,29 @@ public static function polyfill_is_fast()
return PHP_INT_SIZE === 8;
}

/**
* @param int $iterations Number of multiplications to attempt
* @param int $maxTimeout Milliseconds
* @return bool TRUE if we're fast enough, FALSE is not
* @throws SodiumException
*/
public static function runtime_speed_test($iterations, $maxTimeout)
{
if (self::polyfill_is_fast()) {
return true;
}
$end = 0.0;
$start = microtime(true);
$a = ParagonIE_Sodium_Core32_Int64::fromInt(random_int(3, 1 << 16));
for ($i = 0; $i < $iterations; ++$i) {
$b = ParagonIE_Sodium_Core32_Int64::fromInt(random_int(3, 1 << 16));
$a->mulInt64($b);
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Although this isn't a problem right now, FYI this might have a problem in the future with PHP's Dead-Code Elimination optimiser. I've looked at the optimised opcodes at present and it seems OK for now.

See https://www.youtube.com/watch?v=WJJKZM8bruQ#t=28m10s & http://talks.php.net/etsy18#/dce for some examples.

$end = microtime(true);
$diff = ceil(($end - $start) * 1000);
return $diff < $maxTimeout;
}

/**
* Generate a string of bytes from the kernel's CSPRNG.
* Proudly uses /dev/urandom (if getrandom(2) is not available).
Expand Down
8 changes: 8 additions & 0 deletions tests/unit/CompatTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,12 @@ public function testIncrement()
ParagonIE_Sodium_Compat::increment($string);
$this->assertSame("00000220", ParagonIE_Sodium_Core_Util::bin2hex($string));
}

public function testRuntimeSpeed()
{
if (ParagonIE_Sodium_Compat::polyfill_is_fast()) {
return $this->markTestSkipped('Polyfill is fast, no need to test this.');
}
$this->assertTrue(ParagonIE_Sodium_Compat::runtime_speed_test(100, 10));
}
}