1
0

SecureRandomTest.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  6. * SPDX-License-Identifier: AGPL-3.0-or-later
  7. */
  8. namespace Test\Security;
  9. use OC\Security\SecureRandom;
  10. class SecureRandomTest extends \Test\TestCase {
  11. public function stringGenerationProvider() {
  12. return [
  13. [1, 1],
  14. [128, 128],
  15. [256, 256],
  16. [1024, 1024],
  17. [2048, 2048],
  18. [64000, 64000],
  19. ];
  20. }
  21. public static function charCombinations() {
  22. return [
  23. ['CHAR_LOWER', '[a-z]'],
  24. ['CHAR_UPPER', '[A-Z]'],
  25. ['CHAR_DIGITS', '[0-9]'],
  26. ];
  27. }
  28. /** @var SecureRandom */
  29. protected $rng;
  30. protected function setUp(): void {
  31. parent::setUp();
  32. $this->rng = new \OC\Security\SecureRandom();
  33. }
  34. /**
  35. * @dataProvider stringGenerationProvider
  36. */
  37. public function testGetLowStrengthGeneratorLength($length, $expectedLength): void {
  38. $generator = $this->rng;
  39. $this->assertEquals($expectedLength, strlen($generator->generate($length)));
  40. }
  41. /**
  42. * @dataProvider stringGenerationProvider
  43. */
  44. public function testMediumLowStrengthGeneratorLength($length, $expectedLength): void {
  45. $generator = $this->rng;
  46. $this->assertEquals($expectedLength, strlen($generator->generate($length)));
  47. }
  48. /**
  49. * @dataProvider stringGenerationProvider
  50. */
  51. public function testUninitializedGenerate($length, $expectedLength): void {
  52. $this->assertEquals($expectedLength, strlen($this->rng->generate($length)));
  53. }
  54. /**
  55. * @dataProvider charCombinations
  56. */
  57. public function testScheme($charName, $chars): void {
  58. $generator = $this->rng;
  59. $scheme = constant('OCP\Security\ISecureRandom::' . $charName);
  60. $randomString = $generator->generate(100, $scheme);
  61. $matchesRegex = preg_match('/^' . $chars . '+$/', $randomString);
  62. $this->assertSame(1, $matchesRegex);
  63. }
  64. public static function invalidLengths() {
  65. return [
  66. [0],
  67. [-1],
  68. ];
  69. }
  70. /**
  71. * @dataProvider invalidLengths
  72. */
  73. public function testInvalidLengths($length): void {
  74. $this->expectException(\LengthException::class);
  75. $generator = $this->rng;
  76. $generator->generate($length);
  77. }
  78. }