8000 Backport all random improvements · laravel/framework@d18f433 · GitHub
[go: up one dir, main page]

Skip to content

Commit d18f433

Browse files
author
Graham Campbell
committed
Backport all random improvements
1 parent 4e6d4ea commit d18f433

File tree

1 file changed

+31
-11
lines changed

1 file changed

+31
-11
lines changed

src/Illuminate/Support/Str.php

Lines changed: 31 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -213,26 +213,46 @@ public static function plural($value, $count = 2)
213213
*/
214214
public static function random($length = 16)
215215
{
216-
if ( ! function_exists('openssl_random_pseudo_bytes'))
216+
$string = '';
217+
218+
while (($len = strlen($string)) < $length)
217219
{
218-
throw new RuntimeException('OpenSSL extension is required.');
220+
$size = $length - $len;
221+
$bytes = static::randomBytes($size * 2);
222+
$string .= substr(str_replace(['/', '+', '='], '', base64_encode($bytes)), 0, $size);
219223
}
220224

221-
$bytes = openssl_random_pseudo_bytes($length * 2, $strong);
225+
return $string;
226+
}
222227

223-
if ($bytes === false || $strong === false)
228+
/**
229+
* Generate a more truly "random" bytes.
230+
*
231+
* @param int $length
232+
* @return string
233+
*
234+
* @throws \RuntimeException
235+
*/
236+
public static function randomBytes($length = 16)
237+
{
238+
if (function_exists('random_bytes'))
224239
{
225-
throw new RuntimeException('Unable to generate random string.');
240+
$bytes = random_bytes($length);
226241
}
227-
228-
$string = substr(str_replace(array('/', '+', '='), '', base64_encode($bytes)), 0, $length);
229-
230-
while (($len = strlen($string)) < $length)
242+
elseif (function_exists('openssl_random_pseudo_bytes'))
243+
{
244+
$bytes = openssl_random_pseudo_bytes($length, $strong);
245+
if ($bytes === false || $strong === false)
246+
{
247+
throw new RuntimeException('Unable to generate random string.');
248+
}
249+
}
250+
else
231251
{
232-
$string .= static::random($length - $len);
252+
throw new RuntimeException('OpenSSL extension is required for PHP 5 users.');
233253
}
234254

235-
return $string;
255+
return $bytes;
236256
}
237257

238258
/**

0 commit comments

Comments
 (0)
0