Merge pull request #20373 from owncloud/use-random-int-if-it-exists
Use native CSPRNG if available
This commit is contained in:
commit
422d29ae48
|
@ -28,7 +28,7 @@ use OCP\Security\ISecureRandom;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Class SecureRandom provides a layer around RandomLib to generate
|
* Class SecureRandom provides a layer around RandomLib to generate
|
||||||
* secure random strings.
|
* secure random strings. For PHP 7 the native CSPRNG is used.
|
||||||
*
|
*
|
||||||
* Usage:
|
* Usage:
|
||||||
* \OC::$server->getSecureRandom()->getMediumStrengthGenerator()->generate(10);
|
* \OC::$server->getSecureRandom()->getMediumStrengthGenerator()->generate(10);
|
||||||
|
@ -82,11 +82,24 @@ class SecureRandom implements ISecureRandom {
|
||||||
* @return string
|
* @return string
|
||||||
* @throws \Exception If the generator is not initialized.
|
* @throws \Exception If the generator is not initialized.
|
||||||
*/
|
*/
|
||||||
public function generate($length, $characters = '') {
|
public function generate($length,
|
||||||
|
$characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/') {
|
||||||
if(is_null($this->generator)) {
|
if(is_null($this->generator)) {
|
||||||
throw new \Exception('Generator is not initialized.');
|
throw new \Exception('Generator is not initialized.');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if(function_exists('random_int')) {
|
||||||
|
$maxCharIndex = strlen($characters) - 1;
|
||||||
|
$randomString = '';
|
||||||
|
|
||||||
|
while($length > 0) {
|
||||||
|
$randomNumber = random_int(0, $maxCharIndex);
|
||||||
|
$randomString .= $characters[$randomNumber];
|
||||||
|
$length--;
|
||||||
|
}
|
||||||
|
return $randomString;
|
||||||
|
}
|
||||||
|
|
||||||
return $this->generator->generateString($length, $characters);
|
return $this->generator->generateString($length, $characters);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -24,7 +24,7 @@ namespace OCP\Security;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Class SecureRandom provides a layer around RandomLib to generate
|
* Class SecureRandom provides a layer around RandomLib to generate
|
||||||
* secure random numbers.
|
* secure random strings. For PHP 7 the native CSPRNG is used.
|
||||||
*
|
*
|
||||||
* Usage:
|
* Usage:
|
||||||
* $rng = new \OC\Security\SecureRandom();
|
* $rng = new \OC\Security\SecureRandom();
|
||||||
|
@ -76,5 +76,7 @@ interface ISecureRandom {
|
||||||
* @throws \Exception If the generator is not initialized.
|
* @throws \Exception If the generator is not initialized.
|
||||||
* @since 8.0.0
|
* @since 8.0.0
|
||||||
*/
|
*/
|
||||||
public function generate($length, $characters = '');
|
public function generate($length,
|
||||||
|
$characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/');
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue