TokenGenerator.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <?php
  2. /*
  3. * This file is part of the FOSUserBundle package.
  4. *
  5. * (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace FOS\UserBundle\Util;
  11. use Symfony\Component\HttpKernel\Log\LoggerInterface;
  12. class TokenGenerator implements TokenGeneratorInterface
  13. {
  14. private $logger;
  15. private $useOpenSsl;
  16. public function __construct(LoggerInterface $logger = null)
  17. {
  18. $this->logger = $logger;
  19. // determine whether to use OpenSSL
  20. if (defined('PHP_WINDOWS_VERSION_BUILD') && version_compare(PHP_VERSION, '5.3.4', '<')) {
  21. $this->useOpenSsl = false;
  22. } elseif (!function_exists('openssl_random_pseudo_bytes')) {
  23. if (null !== $this->logger) {
  24. $this->logger->notice('It is recommended that you enable the "openssl" extension for random number generation.');
  25. }
  26. $this->useOpenSsl = false;
  27. } else {
  28. $this->useOpenSsl = true;
  29. }
  30. }
  31. public function generateToken()
  32. {
  33. return rtrim(strtr(base64_encode($this->getRandomNumber()), '+/', '-_'), '=');
  34. }
  35. private function getRandomNumber()
  36. {
  37. $nbBytes = 32;
  38. // try OpenSSL
  39. if ($this->useOpenSsl) {
  40. $bytes = openssl_random_pseudo_bytes($nbBytes, $strong);
  41. if (false !== $bytes && true === $strong) {
  42. return $bytes;
  43. }
  44. if (null !== $this->logger) {
  45. $this->logger->info('OpenSSL did not produce a secure random number.');
  46. }
  47. }
  48. return hash('sha256', uniqid(mt_rand(), true), true);
  49. }
  50. }