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 | 40 | public function __construct($keyPath, $passPhrase = null, $keyPermissionsCheck = true) |
|
38 | { |
||
39 | 40 | if (preg_match(self::RSA_KEY_PATTERN, $keyPath)) { |
|
40 | 1 | $keyPath = $this->saveKeyToFile($keyPath); |
|
41 | } |
||
42 | |||
43 | 40 | if (strpos($keyPath, 'file://') !== 0) { |
|
44 | 2 | $keyPath = 'file://' . $keyPath; |
|
45 | } |
||
46 | |||
47 | 40 | if (!file_exists($keyPath) || !is_readable($keyPath)) { |
|
48 | 1 | throw new LogicException(sprintf('Key path "%s" does not exist or is not readable', $keyPath)); |
|
49 | } |
||
50 | |||
51 | 39 | if ($keyPermissionsCheck === true) { |
|
52 | // Verify the permissions of the key |
||
53 | 39 | $keyPathPerms = decoct(fileperms($keyPath) & 0777); |
|
54 | 39 | if (in_array($keyPathPerms, ['400', '440', '600', '640', '660'], true) === false) { |
|
55 | trigger_error(sprintf( |
||
56 | 'Key file "%s" permissions are not correct, recommend changing to 600 or 660 instead of %s', |
||
57 | $keyPath, |
||
58 | $keyPathPerms |
||
59 | ), E_USER_NOTICE); |
||
60 | } |
||
61 | } |
||
62 | |||
63 | 39 | $this->keyPath = $keyPath; |
|
64 | 39 | $this->passPhrase = $passPhrase; |
|
65 | 39 | } |
|
66 | |||
67 | /** |
||
68 | * @param string $key |
||
69 | * |
||
70 | * @throws RuntimeException |
||
71 | * |
||
72 | * @return string |
||
73 | */ |
||
74 | 1 | private function saveKeyToFile($key) |
|
103 | |||
104 | /** |
||
105 | * Retrieve key path. |
||
106 | * |
||
107 | * @return string |
||
108 | */ |
||
109 | 14 | public function getKeyPath() |
|
113 | |||
114 | /** |
||
115 | * Retrieve key pass phrase. |
||
116 | * |
||
117 | * @return null|string |
||
118 | */ |
||
119 | 10 | public function getPassPhrase() |
|
123 | } |
||
124 |