-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathRandom.php
More file actions
52 lines (46 loc) · 1.6 KB
/
Random.php
File metadata and controls
52 lines (46 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<?php
declare(strict_types=1);
namespace SimpleSAML\XMLSecurity\Utils;
use Random\RandomException;
use SimpleSAML\Assert\Assert;
use SimpleSAML\XMLSecurity\Exception\InvalidArgumentException;
use SimpleSAML\XMLSecurity\Exception\RuntimeException;
use ValueError;
use function random_bytes;
/**
* A collection of utilities to generate cryptographically-secure random data.
*
* @package SimpleSAML\XMLSecurity\Utils
*/
class Random
{
/**
* Generate a given amount of cryptographically secure random bytes.
*
* @param positive-int $length The amount of bytes required.
*
* @return string A random string of $length length.
*
* @throws \SimpleSAML\XMLSecurity\Exception\InvalidArgumentException
* If $length is not an integer greater than zero.
* @throws \SimpleSAML\XMLSecurity\Exception\RuntimeException
* If no appropriate sources of cryptographically secure random generators are available.
*/
public static function generateRandomBytes(int $length): string
{
Assert::positiveInteger(
$length,
'Invalid length received to generate random bytes.',
InvalidArgumentException::class,
);
try {
return random_bytes($length);
} catch (ValueError) { // @phpstan-ignore-line
throw new InvalidArgumentException('Invalid length received to generate random bytes.');
} catch (RandomException) {
throw new RuntimeException(
'Cannot generate random bytes, no cryptographically secure random generator available.',
);
}
}
}