Passed
Push — master ( 234432...d8f1ac )
by Tim
01:51
created

Random::generateGUID()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 5
rs 10
1
<?php
2
3
namespace SimpleSAML\XMLSecurity\Utils;
4
5
use Error;
6
use Exception;
7
use SimpleSAML\Assert\Assert;
8
use SimpleSAML\XMLSecurity\Exception\InvalidArgumentException;
9
use SimpleSAML\XMLSecurity\Exception\RuntimeException;
10
11
use function bin2hex;
12
use function random_bytes;
13
use function substr;
14
15
/**
16
 * A collection of utilities to generate cryptographically-secure random data.
17
 *
18
 * @package SimpleSAML\XMLSecurity\Utils
19
 */
20
class Random
21
{
22
    /**
23
     * Generate a given amount of cryptographically secure random bytes.
24
     *
25
     * @param positive-int $length The amount of bytes required.
1 ignored issue
show
Documentation Bug introduced by
The doc comment positive-int at position 0 could not be parsed: Unknown type name 'positive-int' at position 0 in positive-int.
Loading history...
26
     *
27
     * @return string A random string of $length length.
28
     *
29
     * @throws \SimpleSAML\XMLSecurity\Exception\InvalidArgumentException
30
     *   If $length is not an integer greater than zero.
31
     * @throws \SimpleSAML\XMLSecurity\Exception\RuntimeException
32
     *   If no appropriate sources of cryptographically secure random generators are available.
33
     */
34
    public static function generateRandomBytes(int $length): string
35
    {
36
        Assert::positiveInteger(
37
            $length,
38
            'Invalid length received to generate random bytes.',
39
            InvalidArgumentException::class
40
        );
41
42
        try {
43
            return random_bytes($length);
44
        } catch (Error) {
45
            throw new InvalidArgumentException('Invalid length received to generate random bytes.');
46
        } catch (Exception) {
47
            throw new RuntimeException(
48
                'Cannot generate random bytes, no cryptographically secure random generator available.',
49
            );
50
        }
51
    }
52
}
53