Completed
Push — master ( 339298...2994aa )
by
unknown
03:01
created

OpenSslRandomStringGenerator::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.5

Importance

Changes 0
Metric Value
dl 0
loc 9
ccs 3
cts 6
cp 0.5
rs 9.9666
c 0
b 0
f 0
cc 2
nc 2
nop 0
crap 2.5
1
<?php
2
namespace Kunnu\Dropbox\Security;
3
4
use Kunnu\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 \Kunnu\Dropbox\Exceptions\DropboxClientException
24
     */
25 58
    public function __construct()
26
    {
27 58
        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 58
    }
34
35
    /**
36
     * Get a randomly generated secure token
37
     *
38
     * @param  int $length Length of the string to return
39
     *
40
     * @throws \Kunnu\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