1
0

securerandom.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. use \OC\Security\SecureRandom;
  9. class SecureRandomTest extends \Test\TestCase {
  10. public function stringGenerationProvider() {
  11. return array(
  12. array(0, 0),
  13. array(1, 1),
  14. array(128, 128),
  15. array(256, 256),
  16. array(1024, 1024),
  17. array(2048, 2048),
  18. array(64000, 64000),
  19. );
  20. }
  21. public static function charCombinations() {
  22. return array(
  23. array('CHAR_LOWER', '[a-z]'),
  24. array('CHAR_UPPER', '[A-Z]'),
  25. array('CHAR_DIGITS', '[0-9]'),
  26. );
  27. }
  28. /** @var SecureRandom */
  29. protected $rng;
  30. protected function setUp() {
  31. parent::setUp();
  32. $this->rng = new \OC\Security\SecureRandom();
  33. }
  34. /**
  35. * @dataProvider stringGenerationProvider
  36. */
  37. function testGetLowStrengthGeneratorLength($length, $expectedLength) {
  38. $generator = $this->rng->getLowStrengthGenerator();
  39. $this->assertEquals($expectedLength, strlen($generator->generate($length)));
  40. }
  41. /**
  42. * @dataProvider stringGenerationProvider
  43. */
  44. function testMediumLowStrengthGeneratorLength($length, $expectedLength) {
  45. $generator = $this->rng->getMediumStrengthGenerator();
  46. $this->assertEquals($expectedLength, strlen($generator->generate($length)));
  47. }
  48. /**
  49. * @expectedException \Exception
  50. * @expectedExceptionMessage Generator is not initialized
  51. */
  52. function testUninitializedGenerate() {
  53. $this->rng->generate(30);
  54. }
  55. /**
  56. * @dataProvider charCombinations
  57. */
  58. public function testScheme($charName, $chars) {
  59. $generator = $this->rng->getMediumStrengthGenerator();
  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. }