Skip to content

Commit

Permalink
Fix #6103
Browse files Browse the repository at this point in the history
  • Loading branch information
zsturgess committed Jan 4, 2016
1 parent ddd3478 commit ce8b068
Showing 1 changed file with 11 additions and 22 deletions.
33 changes: 11 additions & 22 deletions components/security/secure_tools.rst
Original file line number Diff line number Diff line change
Expand Up @@ -10,38 +10,27 @@ Generating a Secure random Number

Whenever you need to generate a secure random number, you are highly
encouraged to use the Symfony
:class:`Symfony\\Component\\Security\\Core\\Util\\SecureRandom` class::
:phpfunction:`random_bytes` function::

use Symfony\Component\Security\Core\Util\SecureRandom;
$random = random_bytes(10);

$generator = new SecureRandom();
$random = $generator->nextBytes(10);

The
:method:`Symfony\\Component\\Security\\Core\\Util\\SecureRandom::nextBytes`
method returns a random string composed of the number of characters passed as
an argument (10 in the above example).

The SecureRandom class works better when OpenSSL is installed. But when it's
not available, it falls back to an internal algorithm, which needs a seed file
to work correctly. Just pass a file name to enable it::

use Symfony\Component\Security\Core\Util\SecureRandom;

$generator = new SecureRandom('/some/path/to/store/the/seed.txt');

$random = $generator->nextBytes(10);
$hashedRandom = md5($random); // see tip below
The function returns a random string, suitable for cryptographic use, of
the number bytes passed as an argument (10 in the above example).

.. note::

If you're using the Symfony Framework, you can get a secure random number
generator via the ``security.secure_random`` service.

.. note::

PHP versions 7.0.0 and up provide the ``random_bytes()`` function natively,
on lower versions of PHP a polyfill is provided.

.. tip::

The ``nextBytes()`` method returns a binary string which may contain the
The ``random_bytes()`` function returns a binary string which may contain the
``\0`` character. This can cause trouble in several common scenarios, such
as storing this value in a database or including it as part of the URL. The
solution is to hash the value returned by ``nextBytes()`` (to do that, you
solution is to hash the value returned by ``random_bytes()`` (to do that, you
can use a simple ``md5()`` PHP function).

0 comments on commit ce8b068

Please sign in to comment.