Base64UrlSafeTest.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. use ParagonIE\ConstantTime\Base64UrlSafe;
  3. use ParagonIE\ConstantTime\Binary;
  4. /**
  5. * Class Base64UrlSafeTest
  6. */
  7. class Base64UrlSafeTest extends PHPUnit\Framework\TestCase
  8. {
  9. /**
  10. * @covers Base64UrlSafe::encode()
  11. * @covers Base64UrlSafe::decode()
  12. *
  13. * @throws Exception
  14. * @throws TypeError
  15. */
  16. public function testRandom()
  17. {
  18. for ($i = 1; $i < 32; ++$i) {
  19. for ($j = 0; $j < 50; ++$j) {
  20. $random = \random_bytes($i);
  21. $enc = Base64UrlSafe::encode($random);
  22. $this->assertSame(
  23. $random,
  24. Base64UrlSafe::decode($enc)
  25. );
  26. $this->assertSame(
  27. \strtr(\base64_encode($random), '+/', '-_'),
  28. $enc
  29. );
  30. $unpadded = \rtrim($enc, '=');
  31. $this->assertSame(
  32. $unpadded,
  33. Base64UrlSafe::encodeUnpadded($random)
  34. );
  35. $this->assertSame(
  36. $random,
  37. Base64UrlSafe::decode($unpadded)
  38. );
  39. }
  40. }
  41. $random = \random_bytes(1 << 20);
  42. $enc = Base64UrlSafe::encode($random);
  43. $this->assertTrue(Binary::safeStrlen($enc) > 65536);
  44. $this->assertSame(
  45. $random,
  46. Base64UrlSafe::decode($enc)
  47. );
  48. $this->assertSame(
  49. \strtr(\base64_encode($random), '+/', '-_'),
  50. $enc
  51. );
  52. }
  53. }