server/tests/lib/security/securerandom.php

77 lines
1.8 KiB
PHP
Raw Normal View History

<?php
/**
* Copyright (c) 2014 Lukas Reschke <lukas@owncloud.com>
* This file is licensed under the Affero General Public License version 3 or
* later.
* See the COPYING-README file.
*/
2014-09-03 11:51:44 +00:00
use \OC\Security\SecureRandom;
class SecureRandomTest extends \PHPUnit_Framework_TestCase {
public function stringGenerationProvider() {
return array(
array(0, 0),
array(1, 1),
array(128, 128),
array(256, 256),
array(1024, 1024),
array(2048, 2048),
array(64000, 64000),
);
}
2014-09-03 12:13:12 +00:00
public static function charCombinations() {
return array(
array('CHAR_LOWER', '[a-z]'),
array('CHAR_UPPER', '[A-Z]'),
array('CHAR_DIGITS', '[0-9]'),
);
}
2014-09-03 11:51:44 +00:00
/** @var SecureRandom */
protected $rng;
protected function setUp() {
$this->rng = new \OC\Security\SecureRandom();
}
/**
* @dataProvider stringGenerationProvider
*/
function testGetLowStrengthGeneratorLength($length, $expectedLength) {
2014-09-03 11:51:44 +00:00
$generator = $this->rng->getLowStrengthGenerator();
$this->assertEquals($expectedLength, strlen($generator->generate($length)));
}
/**
* @dataProvider stringGenerationProvider
*/
function testMediumLowStrengthGeneratorLength($length, $expectedLength) {
2014-09-03 11:51:44 +00:00
$generator = $this->rng->getMediumStrengthGenerator();
$this->assertEquals($expectedLength, strlen($generator->generate($length)));
}
/**
* @expectedException \Exception
* @expectedExceptionMessage Generator is not initialized
*/
function testUninitializedGenerate() {
2014-09-03 11:51:44 +00:00
$this->rng->generate(30);
}
2014-09-03 12:13:12 +00:00
/**
* @dataProvider charCombinations
*/
public function testScheme($charName, $chars) {
$generator = $this->rng->getMediumStrengthGenerator();
$scheme = constant('OCP\Security\ISecureRandom::' . $charName);
$randomString = $generator->generate(100, $scheme);
$matchesRegex = preg_match('/^'.$chars.'+$/', $randomString);
$this->assertSame(1, $matchesRegex);
}
}