|
1
|
|
|
<?php |
|
2
|
|
|
namespace Dropbox\Security; |
|
3
|
|
|
|
|
4
|
|
|
use InvalidArgumentException; |
|
5
|
|
|
use Dropbox\Exceptions\DropboxClientException; |
|
6
|
|
|
|
|
7
|
|
|
/** |
|
8
|
|
|
* Thanks to Facebook |
|
9
|
|
|
* |
|
10
|
|
|
* @link https://developers.facebook.com/docs/php/RandomStringGeneratorInterface |
|
11
|
|
|
*/ |
|
12
|
|
|
class RandomStringGeneratorFactory |
|
13
|
|
|
{ |
|
14
|
|
|
/** |
|
15
|
|
|
* Make a Random String Generator |
|
16
|
|
|
* |
|
17
|
|
|
* @param null|string|\Dropbox\Security\RandomStringGeneratorInterface $generator |
|
18
|
|
|
* |
|
19
|
|
|
* @throws \Dropbox\Exceptions\DropboxClientException |
|
20
|
|
|
* |
|
21
|
|
|
* @return \Dropbox\Security\RandomStringGeneratorInterface |
|
22
|
|
|
*/ |
|
23
|
58 |
|
public static function makeRandomStringGenerator($generator = null) |
|
24
|
|
|
{ |
|
25
|
|
|
//No generator provided |
|
26
|
58 |
|
if (is_null($generator)) { |
|
27
|
|
|
//Generate default random string generator |
|
28
|
58 |
|
return static::defaultRandomStringGenerator(); |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
|
|
//RandomStringGeneratorInterface |
|
32
|
|
|
if ($generator instanceof RandomStringGeneratorInterface) { |
|
33
|
|
|
return $generator; |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
// Mcrypt |
|
37
|
|
|
if ('mcrypt' === $generator) { |
|
38
|
|
|
return new McryptRandomStringGenerator(); |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
//OpenSSL |
|
42
|
|
|
if ('openssl' === $generator) { |
|
43
|
|
|
return new OpenSslRandomStringGenerator(); |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
//Invalid Argument |
|
47
|
|
|
throw new InvalidArgumentException('The random string generator must be set to "mcrypt", "openssl" or be an instance of Dropbox\Security\RandomStringGeneratorInterface'); |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
/** |
|
51
|
|
|
* Get Default Random String Generator |
|
52
|
|
|
* |
|
53
|
|
|
* @throws \Dropbox\Exceptions\DropboxClientException |
|
54
|
|
|
* |
|
55
|
|
|
* @return RandomStringGeneratorInterface |
|
56
|
|
|
*/ |
|
57
|
58 |
|
protected static function defaultRandomStringGenerator() |
|
58
|
|
|
{ |
|
59
|
|
|
//Mcrypt |
|
60
|
58 |
|
if (function_exists('mcrypt_create_iv')) { |
|
61
|
58 |
|
return new McryptRandomStringGenerator(); |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
//OpenSSL |
|
65
|
|
|
if (function_exists('openssl_random_pseudo_bytes')) { |
|
66
|
|
|
return new OpenSslRandomStringGenerator(); |
|
67
|
|
|
} |
|
68
|
|
|
|
|
69
|
|
|
//Unable to create a random string generator |
|
70
|
|
|
throw new DropboxClientException('Unable to detect a cryptographically secure pseudo-random string generator.'); |
|
71
|
|
|
} |
|
72
|
|
|
} |
|
73
|
|
|
|