@@ -213,26 +213,46 @@ public static function plural($value, $count = 2)
213
213
*/
214
214
public static function random ($ length = 16 )
215
215
{
216
- if ( ! function_exists ('openssl_random_pseudo_bytes ' ))
216
+ $ string = '' ;
217
+
218
+ while (($ len = strlen ($ string )) < $ length )
217
219
{
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 );
219
223
}
220
224
221
- $ bytes = openssl_random_pseudo_bytes ($ length * 2 , $ strong );
225
+ return $ string ;
226
+ }
222
227
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 ' ))
224
239
{
225
- throw new RuntimeException ( ' Unable to generate random string. ' );
240
+ $ bytes = random_bytes ( $ length );
226
241
}
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
231
251
{
232
- $ string .= static :: random ( $ length - $ len );
252
+ throw new RuntimeException ( ' OpenSSL extension is required for PHP 5 users. ' );
233
253
}
234
254
235
- return $ string ;
255
+ return $ bytes ;
236
256
}
237
257
238
258
/**
0 commit comments