Skip to content

Commit 26bb2ae

Browse files
committed
New native implementation of the
`RandomByteGeneratorInterface`
1 parent 664a52b commit 26bb2ae

1 file changed

Lines changed: 47 additions & 0 deletions

File tree

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
<?php
2+
/**
3+
* Robin NTLM
4+
*
5+
* @copyright 2016 Robin Powered, Inc.
6+
* @link https://robinpowered.com/
7+
*/
8+
9+
namespace Robin\Ntlm\Crypt\Random;
10+
11+
use Exception;
12+
use Robin\Ntlm\Crypt\Exception\CryptographicFailureException;
13+
14+
/**
15+
* A cryptographically secure random byte generator implemented using the native
16+
* PHP CSPRNG functions.
17+
*
18+
* @link http://php.net/csprng
19+
*/
20+
class NativeRandomByteGenerator implements RandomByteGeneratorInterface
21+
{
22+
23+
/**
24+
* Methods
25+
*/
26+
27+
/**
28+
* {@inheritDoc}
29+
*/
30+
public function generate($size)
31+
{
32+
try {
33+
$generated = random_bytes($size);
34+
} catch (Error $e) {
35+
// PHP 7+ will throw an `Error`. Catch here to make sure that we don't accidentally catch a polyfilled
36+
// `Error` from a polyfill library, such as https://github.com/paragonie/random_compat
37+
throw $e;
38+
} catch (Exception $e) {
39+
throw CryptographicFailureException::forReasonCode(
40+
CryptographicFailureException::CODE_FOR_RANDOM_DATA_GENERATION_FAILURE,
41+
$e
42+
);
43+
}
44+
45+
return $generated;
46+
}
47+
}

0 commit comments

Comments
 (0)