1 | <?php |
||
5 | final class Shh |
||
6 | { |
||
7 | private const DEFAULT_OPENSSL_GENERATION_CONFIGURATION = [ |
||
8 | 'digest_alg' => 'sha512', |
||
9 | 'private_key_bits' => 4096, |
||
10 | 'private_key_type' => \OPENSSL_KEYTYPE_RSA, |
||
11 | ]; |
||
12 | |||
13 | /** |
||
14 | * @var string |
||
15 | */ |
||
16 | private $publicKey; |
||
17 | |||
18 | /** |
||
19 | * @var string|null |
||
20 | */ |
||
21 | private $privateKey; |
||
22 | |||
23 | /** |
||
24 | * @var string|null |
||
25 | */ |
||
26 | private $passphrase; |
||
27 | |||
28 | /** |
||
29 | * @var resource |
||
30 | */ |
||
31 | private $resource; |
||
32 | |||
33 | /** |
||
34 | * Shh constructor. |
||
35 | */ |
||
36 | public function __construct(string $publicKey, ?string $privateKey = null, ?string $passphrase = null) |
||
37 | { |
||
38 | $this->publicKey = self::normalize($publicKey); |
||
39 | $this->privateKey = null === $privateKey ? null : self::normalize($privateKey); |
||
40 | $this->passphrase = $passphrase; |
||
41 | } |
||
42 | |||
43 | /** |
||
44 | * @return resource |
||
45 | */ |
||
46 | private function getPublicKeyAsResource() |
||
55 | |||
56 | private function freeResource(): void |
||
65 | |||
66 | /** |
||
67 | * @param string $payload |
||
68 | * @return string |
||
69 | */ |
||
70 | public function encrypt(string $payload): string |
||
82 | |||
83 | /** |
||
84 | * @param string $base64EncodedPayload |
||
85 | * @return string |
||
86 | */ |
||
87 | public function decrypt(string $base64EncodedPayload): string |
||
111 | |||
112 | /** |
||
113 | * Generate a new private/public key pair. |
||
114 | * |
||
115 | * @param string|null $passphrase |
||
116 | * @param array $config |
||
117 | * @return array - [publicKey, privateKey] |
||
118 | */ |
||
119 | public static function generateKeyPair(?string $passphrase = null, array $config = []): array |
||
135 | |||
136 | /** |
||
137 | * Change passphrase and return a new private key. |
||
138 | * |
||
139 | * @param string $privateKey |
||
140 | * @param string|null $oldPassphrase |
||
141 | * @param string|null $newPassphrase |
||
142 | * @return string |
||
143 | */ |
||
144 | public static function changePassphrase(string $privateKey, ?string $oldPassphrase, ?string $newPassphrase): string |
||
155 | |||
156 | /** |
||
157 | * @param string $key |
||
158 | * @return string |
||
159 | */ |
||
160 | private static function normalize(string $key): string |
||
164 | } |
||
165 |