1
0

SecureRandomTest.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. [1, 1],
  15. [128, 128],
  16. [256, 256],
  17. [1024, 1024],
  18. [2048, 2048],
  19. [64000, 64000],
  20. ];
  21. }
  22. public static function charCombinations() {
  23. return [
  24. ['CHAR_LOWER', '[a-z]'],
  25. ['CHAR_UPPER', '[A-Z]'],
  26. ['CHAR_DIGITS', '[0-9]'],
  27. ];
  28. }
  29. /** @var SecureRandom */
  30. protected $rng;
  31. protected function setUp(): void {
  32. parent::setUp();
  33. $this->rng = new \OC\Security\SecureRandom();
  34. }
  35. /**
  36. * @dataProvider stringGenerationProvider
  37. */
  38. public function testGetLowStrengthGeneratorLength($length, $expectedLength) {
  39. $generator = $this->rng;
  40. $this->assertEquals($expectedLength, strlen($generator->generate($length)));
  41. }
  42. /**
  43. * @dataProvider stringGenerationProvider
  44. */
  45. public function testMediumLowStrengthGeneratorLength($length, $expectedLength) {
  46. $generator = $this->rng;
  47. $this->assertEquals($expectedLength, strlen($generator->generate($length)));
  48. }
  49. /**
  50. * @dataProvider stringGenerationProvider
  51. */
  52. public function testUninitializedGenerate($length, $expectedLength) {
  53. $this->assertEquals($expectedLength, strlen($this->rng->generate($length)));
  54. }
  55. /**
  56. * @dataProvider charCombinations
  57. */
  58. public function testScheme($charName, $chars) {
  59. $generator = $this->rng;
  60. $scheme = constant('OCP\Security\ISecureRandom::' . $charName);
  61. $randomString = $generator->generate(100, $scheme);
  62. $matchesRegex = preg_match('/^'.$chars.'+$/', $randomString);
  63. $this->assertSame(1, $matchesRegex);
  64. }
  65. public static function invalidLengths() {
  66. return [
  67. [0],
  68. [-1],
  69. ];
  70. }
  71. /**
  72. * @dataProvider invalidLengths
  73. */
  74. public function testInvalidLengths($length) {
  75. $this->expectException(\LengthException::class);
  76. $generator = $this->rng;
  77. $generator->generate($length);
  78. }
  79. }