Skip to content

Commit

Permalink
Throw an exception whenever a zero or negative amount of random bytes…
Browse files Browse the repository at this point in the history
… is requested; note random_bytes fails when you pass in 0
  • Loading branch information
defuse committed Jun 16, 2023
1 parent c03bf47 commit 5d3269f
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
8 changes: 5 additions & 3 deletions src/Core.php
Original file line number Diff line number Diff line change
Expand Up @@ -98,11 +98,13 @@ public static function incrementCounter($ctr, $inc)
*/
public static function secureRandom($octets)
{
if ($octets <= 0) {
throw new Ex\CryptoException(
'A zero or negative amount of random bytes was requested.'
);
}
self::ensureFunctionExists('random_bytes');
try {
if ($octets == 0) {
return "";
}
return \random_bytes(max(1, $octets));
} catch (\Exception $ex) {
throw new Ex\EnvironmentIsBrokenException(
Expand Down
20 changes: 20 additions & 0 deletions test/unit/CoreTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -127,4 +127,24 @@ public function testOurSubstrLengthIsMax()
{
$this->assertSame('bc', Core::ourSubstr('abc', 1, 500));
}

public function testSecureRandomZeroLength()
{
$this->expectException(\Defuse\Crypto\Exception\CryptoException::class);
$this->expectExceptionMessage('zero or negative');
Core::secureRandom(0);
}

public function testSecureRandomNegativeLength()
{
$this->expectException(\Defuse\Crypto\Exception\CryptoException::class);
$this->expectExceptionMessage('zero or negative');
Core::secureRandom(-1);
}

public function testSecureRandomPositiveLength()
{
$x = Core::secureRandom(10);
$this->assertSame(10, strlen($x));
}
}

0 comments on commit 5d3269f

Please sign in to comment.