SecureRandomTest.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. /**
  3. * Copyright (c) 2014 Lukas Reschke <lukas@owncloud.com>
  4. * This file is licensed under the Affero General Public License version 3 or
  5. * later.
  6. * See the COPYING-README file.
  7. */
  8. namespace Test\Security;
  9. use OC\Security\SecureRandom;
  10. class SecureRandomTest extends \Test\TestCase {
  11. public function stringGenerationProvider() {
  12. return [
  13. [0, 0],
  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. }