2014-08-26 13:02:40 -04:00
|
|
|
<?php
|
2019-12-03 13:57:53 -05:00
|
|
|
|
2018-01-14 05:33:53 -05:00
|
|
|
declare(strict_types=1);
|
2014-08-26 13:02:40 -04:00
|
|
|
/**
|
2024-05-23 03:26:56 -04:00
|
|
|
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
|
|
|
|
|
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
|
|
|
|
|
* SPDX-License-Identifier: AGPL-3.0-only
|
2014-08-26 13:02:40 -04:00
|
|
|
*/
|
|
|
|
|
namespace OC\Security;
|
|
|
|
|
|
|
|
|
|
use OCP\Security\ISecureRandom;
|
|
|
|
|
|
|
|
|
|
/**
|
2015-12-11 00:17:47 -05:00
|
|
|
* Class SecureRandom provides a wrapper around the random_int function to generate
|
|
|
|
|
* secure random strings. For PHP 7 the native CSPRNG is used, older versions do
|
|
|
|
|
* use a fallback.
|
2014-08-26 13:02:40 -04:00
|
|
|
*
|
|
|
|
|
* Usage:
|
2023-08-29 17:29:33 -04:00
|
|
|
* \OC::$server->get(ISecureRandom::class)->generate(10);
|
2014-08-26 13:02:40 -04:00
|
|
|
* @package OC\Security
|
|
|
|
|
*/
|
|
|
|
|
class SecureRandom implements ISecureRandom {
|
|
|
|
|
/**
|
2022-05-12 07:58:18 -04:00
|
|
|
* Generate a secure random string of specified length.
|
2015-04-27 07:31:18 -04:00
|
|
|
* @param int $length The length of the generated string
|
2015-11-06 10:24:26 -05:00
|
|
|
* @param string $characters An optional list of characters to use if no character list is
|
2024-08-23 09:10:27 -04:00
|
|
|
* specified all valid base64 characters are used.
|
2022-05-12 07:58:18 -04:00
|
|
|
* @throws \LengthException if an invalid length is requested
|
2014-08-26 13:02:40 -04:00
|
|
|
*/
|
2023-06-26 07:50:56 -04:00
|
|
|
public function generate(
|
|
|
|
|
int $length,
|
|
|
|
|
string $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
|
|
|
|
|
): string {
|
2022-05-12 07:58:18 -04:00
|
|
|
if ($length <= 0) {
|
|
|
|
|
throw new \LengthException('Invalid length specified: ' . $length . ' must be bigger than 0');
|
|
|
|
|
}
|
|
|
|
|
|
2018-01-13 15:39:34 -05:00
|
|
|
$maxCharIndex = \strlen($characters) - 1;
|
2015-12-11 00:17:47 -05:00
|
|
|
$randomString = '';
|
2014-08-26 13:02:40 -04:00
|
|
|
|
2020-04-10 08:19:56 -04:00
|
|
|
while ($length > 0) {
|
2016-01-14 03:24:21 -05:00
|
|
|
$randomNumber = \random_int(0, $maxCharIndex);
|
2015-12-11 00:17:47 -05:00
|
|
|
$randomString .= $characters[$randomNumber];
|
|
|
|
|
$length--;
|
2015-11-06 10:24:26 -05:00
|
|
|
}
|
2015-12-11 00:17:47 -05:00
|
|
|
return $randomString;
|
2014-08-26 13:02:40 -04:00
|
|
|
}
|
|
|
|
|
}
|