OpenSslRandomStringGenerator   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 5
lcom 0
cbo 2
dl 0
loc 55
ccs 0
cts 21
cp 0
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 9 2
A generateString() 0 19 3
1
<?php
2
namespace Dropbox\Security;
3
4
use Dropbox\Exceptions\DropboxClientException;
5
6
/**
7
 * @inheritdoc
8
 */
9
class OpenSslRandomStringGenerator implements RandomStringGeneratorInterface
10
{
11
    use RandomStringGeneratorTrait;
12
13
    /**
14
     * The error message when generating the string fails.
15
     *
16
     * @const string
17
     */
18
    const ERROR_MESSAGE = 'Unable to generate a cryptographically secure pseudo-random string from openssl_random_pseudo_bytes(). ';
19
20
    /**
21
     * Create a new OpenSslRandomStringGenerator instance
22
     *
23
     * @throws \Dropbox\Exceptions\DropboxClientException
24
     */
25
    public function __construct()
26
    {
27
        if (!function_exists('openssl_random_pseudo_bytes')) {
28
            throw new DropboxClientException(
29
                static::ERROR_MESSAGE .
30
                'The function openssl_random_pseudo_bytes() does not exist.'
31
                );
32
        }
33
    }
34
35
    /**
36
     * Get a randomly generated secure token
37
     *
38
     * @param  int $length Length of the string to return
39
     *
40
     * @throws \Dropbox\Exceptions\DropboxClientException
41
     *
42
     * @return string
43
     */
44
    public function generateString($length)
45
    {
46
        $cryptoStrong = false;
47
        //Create Binary String
48
        $binaryString = openssl_random_pseudo_bytes($length, $cryptoStrong);
49
50
        //Unable to create binary string
51
        if ($binaryString === false) {
52
            throw new DropboxClientException(static::ERROR_MESSAGE . 'openssl_random_pseudo_bytes() returned an unknown error.');
53
        }
54
55
        //Binary String is not cryptographically strong
56
        if ($cryptoStrong !== true) {
57
            throw new DropboxClientException(static::ERROR_MESSAGE . 'openssl_random_pseudo_bytes() returned a pseudo-random string but it was not cryptographically secure and cannot be used.');
58
        }
59
60
        //Convert binary to hex
61
        return $this->binToHex($binaryString, $length);
62
    }
63
}
64