Skip to content

Commit 5a35dfc

Browse files
SpomkyMinishlink
authored andcommitted
Key Creation Improvement (#147)
* Key Creation Improvement This modification allow the creation of the local key using OpenSSL. If OpenSSL does not support EC key, the pure PHP method is used a a fallback. * Fix merge * Whitespaces
1 parent 606aff4 commit 5a35dfc

File tree

1 file changed

+56
-2
lines changed

1 file changed

+56
-2
lines changed

src/Encryption.php

Lines changed: 56 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,9 @@
1515

1616
use Base64Url\Base64Url;
1717
use Jose\Component\Core\Util\Ecc\NistCurve;
18+
use Jose\Component\Core\Util\Ecc\Point;
19+
use Jose\Component\Core\Util\Ecc\PrivateKey;
20+
use Jose\Component\Core\Util\Ecc\PublicKey;
1821

1922
class Encryption
2023
{
@@ -52,8 +55,7 @@ public static function encrypt(string $payload, string $userPublicKey, string $u
5255
$curve = NistCurve::curve256();
5356

5457
// get local key pair
55-
$localPrivateKeyObject = $curve->createPrivateKey();
56-
$localPublicKeyObject = $curve->createPublicKey($localPrivateKeyObject);
58+
list($localPublicKeyObject, $localPrivateKeyObject) = self::createLocalKey();
5759
$localPublicKey = hex2bin(Utils::serializePublicKey($localPublicKeyObject));
5860

5961
// get user public key object
@@ -176,4 +178,56 @@ private static function createInfo(string $type, string $context): string
176178

177179
return 'Content-Encoding: '.$type.chr(0).'P-256'.$context;
178180
}
181+
182+
/**
183+
* @return array
184+
*/
185+
private static function createLocalKey(): array
186+
{
187+
try {
188+
return self::createLocalKeyUsingOpenSSL();
189+
} catch (\Exception $e) {
190+
return self::createLocalKeyUsingPurePhpMethod();
191+
}
192+
}
193+
194+
/**
195+
* @return array
196+
*/
197+
private static function createLocalKeyUsingPurePhpMethod(): array
198+
{
199+
$curve = NistCurve::curve256();
200+
$privateKey = $curve->createPrivateKey();
201+
202+
return [
203+
$curve->createPublicKey($privateKey),
204+
$privateKey,
205+
];
206+
}
207+
208+
/**
209+
* @return array
210+
*/
211+
private static function createLocalKeyUsingOpenSSL(): array
212+
{
213+
$key = openssl_pkey_new([
214+
'curve_name' => 'prime256v1',
215+
'private_key_type' => OPENSSL_KEYTYPE_EC,
216+
]);
217+
$res = openssl_pkey_export($key, $out);
218+
if (false === $res) {
219+
throw new \RuntimeException('Unable to create the key');
220+
}
221+
$res = openssl_pkey_get_private($out);
222+
223+
$details = openssl_pkey_get_details($res);
224+
225+
return [
226+
PublicKey::create(Point::create(
227+
gmp_init(bin2hex($details['ec']['x']), 16),
228+
gmp_init(bin2hex($details['ec']['y']), 16)
229+
)),
230+
PrivateKey::create(gmp_init(bin2hex($details['ec']['d']), 16))
231+
];
232+
}
179233
}

0 commit comments

Comments
 (0)