Contributed by
Fabien Potencier
in #4763.

As of Symfony 2.2, we have refactored some security utilities so that you can use them in your own code. These utilities are available in the Symfony\Component\Security\Core\Util namespace.

Generating a secure Random Number

If you need to generate a secure random number, you'd better rely on a strong implementation. Symfony provides one:

1
2
3
4
use Symfony\Component\Security\Core\Util\SecureRandom;

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

The nextBytes() methods returns a random string composed of the number of characters passed as an argument (10 in the above example).

Comparing Strings

Timing attacks are not that well-known, but still, Symfony has protection for them. In Symfony 2.0 and 2.1, this protection was applied to password comparisons done in the Security bundle, but as of Symfony 2.2, it is also available to the developer:

1
2
3
4
use Symfony\Component\Security\Core\Util\StringUtils;

// is password1 equals to password2?
$bool = StringUtils::equals($password1, $password2);

Want to learn more? Have a look at the dedicated documentation.