@@ -9,39 +9,32 @@ Generating a Secure random Number
9
9
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
10
10
11
11
Whenever you need to generate a secure random number, you are highly
12
- encouraged to use the Symfony
13
- :class: ` Symfony \\ Component \\ Security \\ Core \\ Util \\ SecureRandom ` class ::
12
+ encouraged to use the
13
+ :phpfunction: ` random_bytes ` function ::
14
14
15
- use Symfony\Component\Security\Core\Util\SecureRandom ;
15
+ $random = random_bytes(10) ;
16
16
17
- $generator = new SecureRandom();
18
- $random = $generator->nextBytes(10);
19
-
20
- The
21
- :method: `Symfony\\ Component\\ Security\\ Core\\ Util\\ SecureRandom::nextBytes `
22
- method returns a random string composed of the number of characters passed as
23
- an argument (10 in the above example).
24
-
25
- The SecureRandom class works better when OpenSSL is installed. But when it's
26
- not available, it falls back to an internal algorithm, which needs a seed file
27
- to work correctly. Just pass a file name to enable it::
28
-
29
- use Symfony\Component\Security\Core\Util\SecureRandom;
30
-
31
- $generator = new SecureRandom('/some/path/to/store/the/seed.txt');
32
-
33
- $random = $generator->nextBytes(10);
34
- $hashedRandom = md5($random); // see tip below
17
+ The function returns a random string, suitable for cryptographic use, of
18
+ the number bytes passed as an argument (10 in the above example).
35
19
36
20
.. note ::
37
21
38
22
If you're using the Symfony Framework, you can get a secure random number
39
23
generator via the ``security.secure_random `` service.
40
24
25
+ .. note ::
26
+
27
+ PHP 7 and up provide the ``random_bytes() `` function natively, for older
28
+ versions of PHP a polyfill is provided by the `Symfony Polyfill Component `_
29
+ and the `paragonie/random_compat package `_.
30
+
41
31
.. tip ::
42
32
43
- The ``nextBytes () `` method returns a binary string which may contain the
33
+ The ``random_bytes () `` function returns a binary string which may contain the
44
34
``\0 `` character. This can cause trouble in several common scenarios, such
45
35
as storing this value in a database or including it as part of the URL. The
46
- solution is to hash the value returned by ``nextBytes () `` (to do that, you
36
+ solution is to hash the value returned by ``random_bytes () `` (to do that, you
47
37
can use a simple ``md5() `` PHP function).
38
+
39
+ .. _`Symfony Polyfill Component` : https://github.com/symfony/polyfill
40
+ .. _`paragonie/random_compat package` : https://github.com/paragonie/random_compat
0 commit comments