Passed
Push — master ( e54e61...2c6184 )
by Roeland
09:34
created

SecureRandom::getMediumStrengthGenerator()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 2
rs 10
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
/**
4
 * @copyright Copyright (c) 2016, ownCloud, Inc.
5
 *
6
 * @author Lukas Reschke <[email protected]>
7
 * @author Morris Jobke <[email protected]>
8
 *
9
 * @license AGPL-3.0
10
 *
11
 * This code is free software: you can redistribute it and/or modify
12
 * it under the terms of the GNU Affero General Public License, version 3,
13
 * as published by the Free Software Foundation.
14
 *
15
 * This program is distributed in the hope that it will be useful,
16
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18
 * GNU Affero General Public License for more details.
19
 *
20
 * You should have received a copy of the GNU Affero General Public License, version 3,
21
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
22
 *
23
 */
24
25
namespace OC\Security;
26
27
use OCP\Security\ISecureRandom;
28
29
/**
30
 * Class SecureRandom provides a wrapper around the random_int function to generate
31
 * secure random strings. For PHP 7 the native CSPRNG is used, older versions do
32
 * use a fallback.
33
 *
34
 * Usage:
35
 * \OC::$server->getSecureRandom()->generate(10);
36
 * @package OC\Security
37
 */
38
class SecureRandom implements ISecureRandom {
39
	/**
40
	 * Generate a random string of specified length.
41
	 * @param int $length The length of the generated string
42
	 * @param string $characters An optional list of characters to use if no character list is
43
	 * 							specified all valid base64 characters are used.
44
	 * @return string
45
	 */
46
	public function generate(int $length,
47
							 string $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'): string {
48
		$maxCharIndex = \strlen($characters) - 1;
49
		$randomString = '';
50
51
		while($length > 0) {
52
			$randomNumber = \random_int(0, $maxCharIndex);
53
			$randomString .= $characters[$randomNumber];
54
			$length--;
55
		}
56
		return $randomString;
57
	}
58
}
59