Skip to content

Commit ece0c76

Browse files
authored
Merge pull request #7336 from kenjis/fix-random-string-numeric
fix: random_string() numeric
2 parents 4bc7079 + 9ea7ce3 commit ece0c76

3 files changed

Lines changed: 11 additions & 6 deletions

File tree

system/Helpers/text_helper.php

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -543,7 +543,6 @@ function random_string(string $type = 'alnum', int $len = 8): string
543543
{
544544
switch ($type) {
545545
case 'alnum':
546-
case 'numeric':
547546
case 'nozero':
548547
case 'alpha':
549548
switch ($type) {
@@ -555,17 +554,19 @@ function random_string(string $type = 'alnum', int $len = 8): string
555554
$pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
556555
break;
557556

558-
case 'numeric':
559-
$pool = '0123456789';
560-
break;
561-
562557
case 'nozero':
563558
$pool = '123456789';
564559
break;
565560
}
566561

567562
return substr(str_shuffle(str_repeat($pool, (int) ceil($len / strlen($pool)))), 0, $len);
568563

564+
case 'numeric':
565+
$max = 10 ** $len - 1;
566+
$rand = random_int(0, $max);
567+
568+
return sprintf('%0' . $len . 'd', $rand);
569+
569570
case 'md5':
570571
return md5(uniqid((string) mt_rand(), true));
571572

user_guide_src/source/changelogs/v4.3.3.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ SECURITY
1313
********
1414

1515
- **Email:** Added missing TLS 1.3 support.
16+
- **Text Helper:** The :php:func:`random_string()` type **numeric** is now cryptographically secure.
1617

1718
BREAKING
1819
********

user_guide_src/source/helpers/text_helper.rst

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ The following functions are available:
3030
Generates a random string based on the type and length you specify.
3131
Useful for creating passwords or generating random hashes.
3232

33-
.. warning:: Except for type **crypto**, no cryptographically secure
33+
.. warning:: Except for type **numeric** and **crypto**, no cryptographically secure
3434
strings are generated. Therefore, it must not be used for cryptographic
3535
purposes or purposes that requires return values to be unguessable.
3636

@@ -49,6 +49,9 @@ The following functions are available:
4949
.. note:: When you use **crypto**, you must set an even number to the second parameter.
5050
Since v4.2.2, if you set an odd number, ``InvalidArgumentException`` will be thrown.
5151

52+
.. note:: Since v4.3.3, **numeric** uses ``random_int()``. In the previous
53+
versions, it used ``str_shuffle()`` that is not cryptographically secure.
54+
5255
Usage example:
5356

5457
.. literalinclude:: text_helper/002.php

0 commit comments

Comments
 (0)