UriSafeTokenGenerator.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.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 Symfony\Component\Security\Csrf\TokenGenerator;
  11. use Symfony\Component\Security\Core\Util\SecureRandomInterface;
  12. /**
  13. * Generates CSRF tokens.
  14. *
  15. * @author Bernhard Schussek <bernhard.schussek@symfony.com>
  16. */
  17. class UriSafeTokenGenerator implements TokenGeneratorInterface
  18. {
  19. private $entropy;
  20. /**
  21. * Generates URI-safe CSRF tokens.
  22. *
  23. * @param int $entropy The amount of entropy collected for each token (in bits)
  24. */
  25. public function __construct($entropy = 256)
  26. {
  27. if ($entropy instanceof SecureRandomInterface || 2 === \func_num_args()) {
  28. @trigger_error('The '.__METHOD__.' method now requires the entropy to be given as the first argument. The SecureRandomInterface will be removed in 3.0.', E_USER_DEPRECATED);
  29. $this->entropy = 2 === \func_num_args() ? func_get_arg(1) : 256;
  30. } else {
  31. $this->entropy = $entropy;
  32. }
  33. }
  34. /**
  35. * {@inheritdoc}
  36. */
  37. public function generateToken()
  38. {
  39. // Generate an URI safe base64 encoded string that does not contain "+",
  40. // "/" or "=" which need to be URL encoded and make URLs unnecessarily
  41. // longer.
  42. $bytes = random_bytes($this->entropy / 8);
  43. return rtrim(strtr(base64_encode($bytes), '+/', '-_'), '=');
  44. }
  45. }