UriSafeTokenGenerator.php 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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. /**
  12. * Generates CSRF tokens.
  13. *
  14. * @author Bernhard Schussek <bernhard.schussek@symfony.com>
  15. */
  16. class UriSafeTokenGenerator implements TokenGeneratorInterface
  17. {
  18. private $entropy;
  19. /**
  20. * Generates URI-safe CSRF tokens.
  21. *
  22. * @param int $entropy The amount of entropy collected for each token (in bits)
  23. */
  24. public function __construct(int $entropy = 256)
  25. {
  26. $this->entropy = $entropy;
  27. }
  28. /**
  29. * {@inheritdoc}
  30. */
  31. public function generateToken()
  32. {
  33. // Generate an URI safe base64 encoded string that does not contain "+",
  34. // "/" or "=" which need to be URL encoded and make URLs unnecessarily
  35. // longer.
  36. $bytes = random_bytes($this->entropy / 8);
  37. return rtrim(strtr(base64_encode($bytes), '+/', '-_'), '=');
  38. }
  39. }