Skip to content

Commit 8d19639

Browse files
authored
Refactor and optimize key creation (#148)
* Refactor and free resources * Don't use intermediary PEM export Fix #5
1 parent 5a35dfc commit 8d19639

File tree

1 file changed

+15
-11
lines changed

1 file changed

+15
-11
lines changed

src/Encryption.php

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ public static function encrypt(string $payload, string $userPublicKey, string $u
5555
$curve = NistCurve::curve256();
5656

5757
// get local key pair
58-
list($localPublicKeyObject, $localPrivateKeyObject) = self::createLocalKey();
58+
list($localPublicKeyObject, $localPrivateKeyObject) = self::createLocalKeyObject();
5959
$localPublicKey = hex2bin(Utils::serializePublicKey($localPublicKeyObject));
6060

6161
// get user public key object
@@ -182,19 +182,19 @@ private static function createInfo(string $type, string $context): string
182182
/**
183183
* @return array
184184
*/
185-
private static function createLocalKey(): array
185+
private static function createLocalKeyObject(): array
186186
{
187187
try {
188-
return self::createLocalKeyUsingOpenSSL();
188+
return self::createLocalKeyObjectUsingOpenSSL();
189189
} catch (\Exception $e) {
190-
return self::createLocalKeyUsingPurePhpMethod();
190+
return self::createLocalKeyObjectUsingPurePhpMethod();
191191
}
192192
}
193193

194194
/**
195195
* @return array
196196
*/
197-
private static function createLocalKeyUsingPurePhpMethod(): array
197+
private static function createLocalKeyObjectUsingPurePhpMethod(): array
198198
{
199199
$curve = NistCurve::curve256();
200200
$privateKey = $curve->createPrivateKey();
@@ -208,19 +208,23 @@ private static function createLocalKeyUsingPurePhpMethod(): array
208208
/**
209209
* @return array
210210
*/
211-
private static function createLocalKeyUsingOpenSSL(): array
211+
private static function createLocalKeyObjectUsingOpenSSL(): array
212212
{
213-
$key = openssl_pkey_new([
213+
$keyResource = openssl_pkey_new([
214214
'curve_name' => 'prime256v1',
215215
'private_key_type' => OPENSSL_KEYTYPE_EC,
216216
]);
217-
$res = openssl_pkey_export($key, $out);
218-
if (false === $res) {
217+
218+
if (!$keyResource) {
219219
throw new \RuntimeException('Unable to create the key');
220220
}
221-
$res = openssl_pkey_get_private($out);
222221

223-
$details = openssl_pkey_get_details($res);
222+
$details = openssl_pkey_get_details($keyResource);
223+
openssl_pkey_free($keyResource);
224+
225+
if (!$details) {
226+
throw new \RuntimeException('Unable to get the key details');
227+
}
224228

225229
return [
226230
PublicKey::create(Point::create(

0 commit comments

Comments
 (0)