2010-12-05 01:18:19 +01:00
|
|
|
<?php
|
2016-06-23 01:37:22 +02:00
|
|
|
|
|
|
|
namespace SilverStripe\Security;
|
|
|
|
|
2017-05-19 12:18:56 +02:00
|
|
|
use Error;
|
2016-06-23 01:37:22 +02:00
|
|
|
use Exception;
|
2018-11-01 07:51:15 +01:00
|
|
|
use SilverStripe\Dev\Deprecation;
|
2016-06-23 01:37:22 +02:00
|
|
|
|
2010-12-05 01:18:19 +01:00
|
|
|
/**
|
2017-05-19 12:18:56 +02:00
|
|
|
* Convenience class for generating cryptographically secure pseudo-random strings/tokens
|
2010-12-05 01:18:19 +01:00
|
|
|
*/
|
2016-11-29 00:31:16 +01:00
|
|
|
class RandomGenerator
|
|
|
|
{
|
|
|
|
/**
|
2017-05-19 12:18:56 +02:00
|
|
|
* @return string A 128-character, randomly generated ASCII string
|
|
|
|
* @throws Exception If no suitable CSPRNG is installed
|
2018-11-05 12:07:24 +01:00
|
|
|
* @deprecated 4.4.0:5.0.0
|
2016-11-29 00:31:16 +01:00
|
|
|
*/
|
|
|
|
public function generateEntropy()
|
|
|
|
{
|
2018-11-01 07:51:15 +01:00
|
|
|
Deprecation::notice('4.4', __METHOD__ . ' has been deprecated. Use random_bytes instead');
|
|
|
|
|
2017-05-19 12:18:56 +02:00
|
|
|
try {
|
2016-12-29 11:46:08 +01:00
|
|
|
return bin2hex(random_bytes(64));
|
2017-05-19 12:18:56 +02:00
|
|
|
} catch (Error $e) {
|
|
|
|
throw $e; // This is required so that Error exceptions in PHP 5 aren't caught below
|
|
|
|
} catch (Exception $e) {
|
|
|
|
throw new Exception(
|
|
|
|
'It appears there is no suitable CSPRNG (random number generator) installed. '
|
|
|
|
. 'Please review the server requirements documentation: '
|
|
|
|
. 'https://docs.silverstripe.org/en/getting_started/server_requirements/'
|
|
|
|
);
|
2016-12-29 11:46:08 +01:00
|
|
|
}
|
2016-11-29 00:31:16 +01:00
|
|
|
}
|
2012-11-08 04:33:19 +01:00
|
|
|
|
2016-11-29 00:31:16 +01:00
|
|
|
/**
|
|
|
|
* Generates a random token that can be used for session IDs, CSRF tokens etc., based on
|
|
|
|
* hash algorithms.
|
|
|
|
*
|
|
|
|
* If you are using it as a password equivalent (e.g. autologin token) do NOT store it
|
|
|
|
* in the database as a plain text but encrypt it with Member::encryptWithUserSettings.
|
|
|
|
*
|
2017-05-19 12:18:56 +02:00
|
|
|
* @param string $algorithm Any identifier listed in hash_algos() (Default: whirlpool)
|
|
|
|
* @return string Returned length will depend on the used $algorithm
|
2018-11-01 07:51:15 +01:00
|
|
|
* @throws Exception When there is no valid source of CSPRNG
|
2016-11-29 00:31:16 +01:00
|
|
|
*/
|
|
|
|
public function randomToken($algorithm = 'whirlpool')
|
|
|
|
{
|
2018-11-01 07:51:15 +01:00
|
|
|
return hash($algorithm, random_bytes(64));
|
2016-11-29 00:31:16 +01:00
|
|
|
}
|
2012-11-08 04:33:19 +01:00
|
|
|
}
|