Completed
Push — fix-2494 ( 3153ee...40d9bb )
by Sam
13:43 queued 06:38
created

RandomGenerator   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 36
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Importance

Changes 0
Metric Value
dl 0
loc 36
rs 10
c 0
b 0
f 0
wmc 4
lcom 0
cbo 1

2 Methods

Rating   Name   Duplication   Size   Complexity  
A generateEntropy() 0 14 3
A randomToken() 0 4 1
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