Skip to content

Commit 8a47a7e

Browse files
committed
fix: random_string('crypto') may return string less than $len or ErrorException
1 parent 4df89ed commit 8a47a7e

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

system/Helpers/text_helper.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -573,6 +573,12 @@ function random_string(string $type = 'alnum', int $len = 8): string
573573
return sha1(uniqid((string) mt_rand(), true));
574574

575575
case 'crypto':
576+
if ($len % 2 !== 0) {
577+
throw new InvalidArgumentException(
578+
'You must set an even number to the second parameter when you use `crypto`.'
579+
);
580+
}
581+
576582
return bin2hex(random_bytes($len / 2));
577583
}
578584
// 'basic' type treated as default

tests/system/Helpers/TextHelperTest.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
namespace CodeIgniter\Helpers;
1313

1414
use CodeIgniter\Test\CIUnitTestCase;
15+
use InvalidArgumentException;
1516

1617
/**
1718
* @internal
@@ -113,6 +114,19 @@ public function testRandomString()
113114
$this->assertSame(40, strlen($random = random_string('sha1')));
114115
}
115116

117+
/**
118+
* @see https://github.com/codeigniter4/CodeIgniter4/issues/6330
119+
*/
120+
public function testRandomStringCryptoOddNumber()
121+
{
122+
$this->expectException(InvalidArgumentException::class);
123+
$this->expectExceptionMessage(
124+
'You must set an even number to the second parameter when you use `crypto`'
125+
);
126+
127+
random_string('crypto', 9);
128+
}
129+
116130
public function testIncrementString()
117131
{
118132
$this->assertSame('my-test_1', increment_string('my-test'));

0 commit comments

Comments
 (0)