Merge pull request #7336 from kenjis/fix-random-string-numeric

fix: random_string() numeric
This commit is contained in:
kenjis 2023-03-07 09:29:48 +09:00 committed by GitHub
commit ece0c7673d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 11 additions and 6 deletions

View File

@ -543,7 +543,6 @@ if (! function_exists('random_string')) {
{
switch ($type) {
case 'alnum':
case 'numeric':
case 'nozero':
case 'alpha':
switch ($type) {
@ -555,10 +554,6 @@ if (! function_exists('random_string')) {
$pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
break;
case 'numeric':
$pool = '0123456789';
break;
case 'nozero':
$pool = '123456789';
break;
@ -566,6 +561,12 @@ if (! function_exists('random_string')) {
return substr(str_shuffle(str_repeat($pool, (int) ceil($len / strlen($pool)))), 0, $len);
case 'numeric':
$max = 10 ** $len - 1;
$rand = random_int(0, $max);
return sprintf('%0' . $len . 'd', $rand);
case 'md5':
return md5(uniqid((string) mt_rand(), true));

View File

@ -13,6 +13,7 @@ SECURITY
********
- **Email:** Added missing TLS 1.3 support.
- **Text Helper:** The :php:func:`random_string()` type **numeric** is now cryptographically secure.
BREAKING
********

View File

@ -30,7 +30,7 @@ The following functions are available:
Generates a random string based on the type and length you specify.
Useful for creating passwords or generating random hashes.
.. warning:: Except for type **crypto**, no cryptographically secure
.. warning:: Except for type **numeric** and **crypto**, no cryptographically secure
strings are generated. Therefore, it must not be used for cryptographic
purposes or purposes that requires return values to be unguessable.
@ -49,6 +49,9 @@ The following functions are available:
.. note:: When you use **crypto**, you must set an even number to the second parameter.
Since v4.2.2, if you set an odd number, ``InvalidArgumentException`` will be thrown.
.. note:: Since v4.3.3, **numeric** uses ``random_int()``. In the previous
versions, it used ``str_shuffle()`` that is not cryptographically secure.
Usage example:
.. literalinclude:: text_helper/002.php