|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* Cryptography key holder. |
|
4
|
|
|
* |
|
5
|
|
|
* @author Julián Gutiérrez <[email protected]> |
|
6
|
|
|
* @copyright Copyright (c) Alex Bilbie |
|
7
|
|
|
* @license http://mit-license.org/ |
|
8
|
|
|
* |
|
9
|
|
|
* @link https://github.com/thephpleague/oauth2-server |
|
10
|
|
|
*/ |
|
11
|
|
|
|
|
12
|
|
|
namespace League\OAuth2\Server; |
|
13
|
|
|
|
|
14
|
|
|
class CryptKey |
|
15
|
|
|
{ |
|
16
|
|
|
const RSA_KEY_PATTERN = |
|
17
|
|
|
'/^(-----BEGIN (RSA )?(PUBLIC|PRIVATE) KEY-----\n)(.|\n)+(-----END (RSA )?(PUBLIC|PRIVATE) KEY-----)$/'; |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* @var string |
|
21
|
|
|
*/ |
|
22
|
|
|
protected $keyPath; |
|
23
|
|
|
|
|
24
|
|
|
/** |
|
25
|
|
|
* @var null|string |
|
26
|
|
|
*/ |
|
27
|
|
|
protected $passPhrase; |
|
28
|
|
|
|
|
29
|
|
|
/** |
|
30
|
|
|
* @param string $keyPath |
|
31
|
|
|
* @param null|string $passPhrase |
|
32
|
|
|
*/ |
|
33
|
|
|
public function __construct($keyPath, $passPhrase = null) |
|
34
|
|
|
{ |
|
35
|
|
|
if (preg_match(self::RSA_KEY_PATTERN, $keyPath)) { |
|
36
|
|
|
$keyPath = $this->saveKeyToFile($keyPath); |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
if (strpos($keyPath, 'file://') !== 0) { |
|
40
|
|
|
$keyPath = 'file://' . $keyPath; |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
if (!file_exists($keyPath) || !is_readable($keyPath)) { |
|
44
|
|
|
throw new \LogicException(sprintf('Key path "%s" does not exist or is not readable', $keyPath)); |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
$this->keyPath = $keyPath; |
|
48
|
|
|
$this->passPhrase = $passPhrase; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
/** |
|
52
|
|
|
* @param string $key |
|
53
|
|
|
* |
|
54
|
|
|
* @return string |
|
55
|
|
|
*/ |
|
56
|
|
|
private function saveKeyToFile($key) |
|
57
|
|
|
{ |
|
58
|
|
|
$keyPath = sys_get_temp_dir() . '/' . sha1($key) . '.key'; |
|
59
|
|
|
|
|
60
|
|
|
if (!file_exists($keyPath) && !touch($keyPath)) { |
|
61
|
|
|
throw new \RuntimeException('"%s" key file could not be created', $keyPath); |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
file_put_contents($keyPath, $key); |
|
65
|
|
|
|
|
66
|
|
|
return 'file://' . $keyPath; |
|
67
|
|
|
} |
|
68
|
|
|
|
|
69
|
|
|
/** |
|
70
|
|
|
* Retrieve key path. |
|
71
|
|
|
* |
|
72
|
|
|
* @return string |
|
73
|
|
|
*/ |
|
74
|
|
|
public function getKeyPath() |
|
75
|
|
|
{ |
|
76
|
|
|
return $this->keyPath; |
|
77
|
|
|
} |
|
78
|
|
|
|
|
79
|
|
|
/** |
|
80
|
|
|
* Retrieve key pass phrase. |
|
81
|
|
|
* |
|
82
|
|
|
* @return null|string |
|
83
|
|
|
*/ |
|
84
|
|
|
public function getPassPhrase() |
|
85
|
|
|
{ |
|
86
|
|
|
return $this->passPhrase; |
|
87
|
|
|
} |
|
88
|
|
|
} |
|
89
|
|
|
|