Completed
Push — master ( 2994aa...19d116 )
by Patrick
08:28
created

OpenSslRandomStringGenerator::generateString()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 19
ccs 0
cts 8
cp 0
rs 9.6333
c 0
b 0
f 0
cc 3
nc 3
nop 1
crap 12
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