Completed
Push — master ( 80bff0...2aa3b5 )
by Damian
08:40
created

RandomGenerator::generateEntropy()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 10
c 1
b 0
f 0
nc 3
nop 0
dl 0
loc 14
rs 9.4285
1
<?php
2
3
namespace SilverStripe\Security;
4
5
use Error;
6
use Exception;
7
8
/**
9
 * Convenience class for generating cryptographically secure pseudo-random strings/tokens
10
 */
11
class RandomGenerator
12
{
13
    /**
14
     * @return string A 128-character, randomly generated ASCII string
15
     * @throws Exception If no suitable CSPRNG is installed
16
     */
17
    public function generateEntropy()
18
    {
19
        try {
20
            return bin2hex(random_bytes(64));
21
        } catch (Error $e) {
22
            throw $e; // This is required so that Error exceptions in PHP 5 aren't caught below
23
        } catch (Exception $e) {
24
            throw new Exception(
25
                'It appears there is no suitable CSPRNG (random number generator) installed. '
26
                . 'Please review the server requirements documentation: '
27
                . 'https://docs.silverstripe.org/en/getting_started/server_requirements/'
28
            );
29
        }
30
    }
31
32
    /**
33
     * Generates a random token that can be used for session IDs, CSRF tokens etc., based on
34
     * hash algorithms.
35
     *
36
     * If you are using it as a password equivalent (e.g. autologin token) do NOT store it
37
     * in the database as a plain text but encrypt it with Member::encryptWithUserSettings.
38
     *
39
     * @param string $algorithm Any identifier listed in hash_algos() (Default: whirlpool)
40
     * @return string Returned length will depend on the used $algorithm
41
     */
42
    public function randomToken($algorithm = 'whirlpool')
43
    {
44
        return hash($algorithm, $this->generateEntropy());
45
    }
46
}
47