2014-08-26 19:02:40 +02:00
|
|
|
<?php
|
2019-12-03 19:57:53 +01:00
|
|
|
|
2018-01-14 11:33:53 +01:00
|
|
|
declare(strict_types=1);
|
2014-08-26 19:02:40 +02:00
|
|
|
/**
|
2024-05-23 09:26:56 +02: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 19:02:40 +02:00
|
|
|
*/
|
|
|
|
namespace OC\Security;
|
|
|
|
|
|
|
|
use OCP\Security\ISecureRandom;
|
|
|
|
|
|
|
|
/**
|
2015-12-11 06:17:47 +01: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 19:02:40 +02:00
|
|
|
*
|
|
|
|
* Usage:
|
2023-08-29 16:29:33 -05:00
|
|
|
* \OC::$server->get(ISecureRandom::class)->generate(10);
|
2014-08-26 19:02:40 +02:00
|
|
|
* @package OC\Security
|
|
|
|
*/
|
|
|
|
class SecureRandom implements ISecureRandom {
|
|
|
|
/**
|
2022-05-12 13:58:18 +02:00
|
|
|
* Generate a secure random string of specified length.
|
2015-04-27 13:31:18 +02:00
|
|
|
* @param int $length The length of the generated string
|
2015-11-06 16:24:26 +01:00
|
|
|
* @param string $characters An optional list of characters to use if no character list is
|
2015-02-13 11:35:12 +01:00
|
|
|
* specified all valid base64 characters are used.
|
2022-05-12 13:58:18 +02:00
|
|
|
* @throws \LengthException if an invalid length is requested
|
2014-08-26 19:02:40 +02:00
|
|
|
*/
|
2023-06-26 15:20:56 +03:30
|
|
|
public function generate(
|
|
|
|
int $length,
|
|
|
|
string $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
|
|
|
|
): string {
|
2022-05-12 13:58:18 +02:00
|
|
|
if ($length <= 0) {
|
|
|
|
throw new \LengthException('Invalid length specified: ' . $length . ' must be bigger than 0');
|
|
|
|
}
|
|
|
|
|
2018-01-13 21:39:34 +01:00
|
|
|
$maxCharIndex = \strlen($characters) - 1;
|
2015-12-11 06:17:47 +01:00
|
|
|
$randomString = '';
|
2014-08-26 19:02:40 +02:00
|
|
|
|
2015-12-11 06:17:47 +01:00
|
|
|
while ($length > 0) {
|
2016-01-14 09:24:21 +01:00
|
|
|
$randomNumber = \random_int(0, $maxCharIndex);
|
2015-12-11 06:17:47 +01:00
|
|
|
$randomString .= $characters[$randomNumber];
|
|
|
|
$length--;
|
2015-11-06 16:24:26 +01:00
|
|
|
}
|
2015-12-11 06:17:47 +01:00
|
|
|
return $randomString;
|
2014-08-26 19:02:40 +02:00
|
|
|
}
|
|
|
|
}
|