From 5d3269ff9cf0700280f33b5b7acdec9f3c120db9 Mon Sep 17 00:00:00 2001 From: Taylor Hornby Date: Fri, 16 Jun 2023 15:42:07 -0600 Subject: [PATCH] Throw an exception whenever a zero or negative amount of random bytes is requested; note random_bytes fails when you pass in 0 --- src/Core.php | 8 +++++--- test/unit/CoreTest.php | 20 ++++++++++++++++++++ 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/src/Core.php b/src/Core.php index 337ad58..bd99a1a 100644 --- a/src/Core.php +++ b/src/Core.php @@ -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( diff --git a/test/unit/CoreTest.php b/test/unit/CoreTest.php index 692b2fa..69cfe08 100644 --- a/test/unit/CoreTest.php +++ b/test/unit/CoreTest.php @@ -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)); + } }