SecureRandomTest.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * Copyright (c) 2014 Lukas Reschke <lukas@owncloud.com>
  5. * This file is licensed under the Affero General Public License version 3 or
  6. * later.
  7. * See the COPYING-README file.
  8. */
  9. namespace Test\Security;
  10. use OC\Security\SecureRandom;
  11. class SecureRandomTest extends \Test\TestCase {
  12. public function stringGenerationProvider() {
  13. return [
  14. [0, 0],
  15. [1, 1],
  16. [128, 128],
  17. [256, 256],
  18. [1024, 1024],
  19. [2048, 2048],
  20. [64000, 64000],
  21. ];
  22. }
  23. public static function charCombinations() {
  24. return [
  25. ['CHAR_LOWER', '[a-z]'],
  26. ['CHAR_UPPER', '[A-Z]'],
  27. ['CHAR_DIGITS', '[0-9]'],
  28. ];
  29. }
  30. /** @var SecureRandom */
  31. protected $rng;
  32. protected function setUp(): void {
  33. parent::setUp();
  34. $this->rng = new \OC\Security\SecureRandom();
  35. }
  36. /**
  37. * @dataProvider stringGenerationProvider
  38. */
  39. public function testGetLowStrengthGeneratorLength($length, $expectedLength) {
  40. $generator = $this->rng;
  41. $this->assertEquals($expectedLength, strlen($generator->generate($length)));
  42. }
  43. /**
  44. * @dataProvider stringGenerationProvider
  45. */
  46. public function testMediumLowStrengthGeneratorLength($length, $expectedLength) {
  47. $generator = $this->rng;
  48. $this->assertEquals($expectedLength, strlen($generator->generate($length)));
  49. }
  50. /**
  51. * @dataProvider stringGenerationProvider
  52. */
  53. public function testUninitializedGenerate($length, $expectedLength) {
  54. $this->assertEquals($expectedLength, strlen($this->rng->generate($length)));
  55. }
  56. /**
  57. * @dataProvider charCombinations
  58. */
  59. public function testScheme($charName, $chars) {
  60. $generator = $this->rng;
  61. $scheme = constant('OCP\Security\ISecureRandom::' . $charName);
  62. $randomString = $generator->generate(100, $scheme);
  63. $matchesRegex = preg_match('/^'.$chars.'+$/', $randomString);
  64. $this->assertSame(1, $matchesRegex);
  65. }
  66. }