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 | /** |
||
57 | * @param string $payload |
||
58 | * @return string |
||
59 | */ |
||
60 | public function encrypt(string $payload): string |
||
71 | |||
72 | /** |
||
73 | * @param string $base64EncodedPayload |
||
74 | * @return string |
||
75 | */ |
||
76 | public function decrypt(string $base64EncodedPayload): string |
||
100 | |||
101 | /** |
||
102 | * Generate a new private/public key pair. |
||
103 | * |
||
104 | * @param string|null $passphrase |
||
105 | * @param array $config |
||
106 | * @return array - [privateKey, publicKey] |
||
107 | */ |
||
108 | public static function generateKeyPair(?string $passphrase = null, array $config = self::DEFAULT_OPENSSL_GENERATION_CONFIGURATION): array |
||
123 | |||
124 | /** |
||
125 | * Change passphrase and return a new private key. |
||
126 | * |
||
127 | * @param string $privateKey |
||
128 | * @param string|null $oldPassphrase |
||
129 | * @param string|null $newPassphrase |
||
130 | * @return string |
||
131 | */ |
||
132 | public static function changePassphrase(string $privateKey, ?string $oldPassphrase, ?string $newPassphrase): string |
||
143 | |||
144 | /** |
||
145 | * @param string $key |
||
146 | * @return string |
||
147 | */ |
||
148 | private static function normalize(string $key): string |
||
152 | } |
||
153 |