PageRenderTime 61ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/Util/TokenGenerator.php

https://bitbucket.org/Ibit/fosuserbundle
PHP | 62 lines | 40 code | 12 blank | 10 comment | 8 complexity | 7e2137076238a40412ca48ffb28fc296 MD5 | raw file
  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 base_convert(bin2hex($this->getRandomNumber()), 16, 36);
  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. }