SecureRandomTest.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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 array(
  13. array(0, 0),
  14. array(1, 1),
  15. array(128, 128),
  16. array(256, 256),
  17. array(1024, 1024),
  18. array(2048, 2048),
  19. array(64000, 64000),
  20. );
  21. }
  22. public static function charCombinations() {
  23. return array(
  24. array('CHAR_LOWER', '[a-z]'),
  25. array('CHAR_UPPER', '[A-Z]'),
  26. array('CHAR_DIGITS', '[0-9]'),
  27. );
  28. }
  29. /** @var SecureRandom */
  30. protected $rng;
  31. protected function setUp() {
  32. parent::setUp();
  33. $this->rng = new \OC\Security\SecureRandom();
  34. }
  35. /**
  36. * @dataProvider stringGenerationProvider
  37. */
  38. function testGetLowStrengthGeneratorLength($length, $expectedLength) {
  39. $generator = $this->rng;
  40. $this->assertEquals($expectedLength, strlen($generator->generate($length)));
  41. }
  42. /**
  43. * @dataProvider stringGenerationProvider
  44. */
  45. function testMediumLowStrengthGeneratorLength($length, $expectedLength) {
  46. $generator = $this->rng;
  47. $this->assertEquals($expectedLength, strlen($generator->generate($length)));
  48. }
  49. /**
  50. * @dataProvider stringGenerationProvider
  51. */
  52. 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. }