1 | <?php |
||
17 | class CryptKey |
||
18 | { |
||
19 | const RSA_KEY_PATTERN = |
||
20 | '/^(-----BEGIN (RSA )?(PUBLIC|PRIVATE) KEY-----)\R.*(-----END (RSA )?(PUBLIC|PRIVATE) KEY-----)\R?$/s'; |
||
21 | |||
22 | /** |
||
23 | * @var string |
||
24 | */ |
||
25 | protected $keyPath; |
||
26 | |||
27 | /** |
||
28 | * @var null|string |
||
29 | */ |
||
30 | protected $passPhrase; |
||
31 | |||
32 | /** |
||
33 | * @param string $keyPath |
||
34 | * @param null|string $passPhrase |
||
35 | * @param bool $keyPermissionsCheck |
||
36 | */ |
||
37 | 55 | public function __construct($keyPath, $passPhrase = null, $keyPermissionsCheck = true) |
|
38 | { |
||
39 | 55 | if ($rsaMatch = preg_match(static::RSA_KEY_PATTERN, $keyPath)) { |
|
40 | 1 | $keyPath = $this->saveKeyToFile($keyPath); |
|
41 | 54 | } elseif ($rsaMatch === false) { |
|
42 | 1 | throw new \RuntimeException( |
|
43 | 1 | sprintf('PCRE error [%d] encountered during key match attempt', preg_last_error()) |
|
44 | ); |
||
45 | } |
||
46 | |||
47 | 54 | if (strpos($keyPath, 'file://') !== 0) { |
|
48 | 2 | $keyPath = 'file://' . $keyPath; |
|
49 | } |
||
50 | |||
51 | 54 | if (!file_exists($keyPath) || !is_readable($keyPath)) { |
|
52 | 1 | throw new LogicException(sprintf('Key path "%s" does not exist or is not readable', $keyPath)); |
|
53 | } |
||
54 | |||
55 | 53 | if ($keyPermissionsCheck === true) { |
|
56 | // Verify the permissions of the key |
||
57 | 53 | $keyPathPerms = decoct(fileperms($keyPath) & 0777); |
|
58 | 53 | if (in_array($keyPathPerms, ['400', '440', '600', '640', '660'], true) === false) { |
|
59 | trigger_error(sprintf( |
||
60 | 'Key file "%s" permissions are not correct, recommend changing to 600 or 660 instead of %s', |
||
61 | $keyPath, |
||
62 | $keyPathPerms |
||
63 | ), E_USER_NOTICE); |
||
64 | } |
||
65 | } |
||
66 | |||
67 | 53 | $this->keyPath = $keyPath; |
|
68 | 53 | $this->passPhrase = $passPhrase; |
|
69 | 53 | } |
|
70 | |||
71 | /** |
||
72 | * @param string $key |
||
73 | * |
||
74 | * @throws RuntimeException |
||
75 | * |
||
76 | * @return string |
||
77 | */ |
||
78 | 1 | private function saveKeyToFile($key) |
|
107 | |||
108 | /** |
||
109 | * Retrieve key path. |
||
110 | * |
||
111 | * @return string |
||
112 | */ |
||
113 | 14 | public function getKeyPath() |
|
117 | |||
118 | /** |
||
119 | * Retrieve key pass phrase. |
||
120 | * |
||
121 | * @return null|string |
||
122 | */ |
||
123 | 10 | public function getPassPhrase() |
|
127 | } |
||
128 |