|
7 | 7 | use InvalidArgumentException; |
8 | 8 | use OpenSSLCertificate; |
9 | 9 | use ParagonIE\ConstantTime\Base64UrlSafe; |
| 10 | +use ParagonIE\Sodium\Core\Ed25519; |
10 | 11 | use RuntimeException; |
11 | 12 | use SpomkyLabs\Pki\CryptoEncoding\PEM; |
12 | 13 | use SpomkyLabs\Pki\CryptoTypes\Asymmetric\PrivateKey; |
13 | 14 | use SpomkyLabs\Pki\CryptoTypes\Asymmetric\PublicKey; |
14 | 15 | use Throwable; |
15 | 16 | use function array_key_exists; |
| 17 | +use function assert; |
16 | 18 | use function count; |
17 | 19 | use function extension_loaded; |
18 | 20 | use function in_array; |
@@ -258,17 +260,31 @@ private static function tryToLoadOtherKeyTypes(string $input): array |
258 | 260 | */ |
259 | 261 | private static function populatePoints(PrivateKey $key, array $values): array |
260 | 262 | { |
261 | | - if (($values['crv'] === 'Ed25519' || $values['crv'] === 'X25519')) { |
262 | | - if (! extension_loaded('sodium')) { |
263 | | - throw new RuntimeException('Please install the Sodium extension'); |
264 | | - } |
265 | | - $x = sodium_crypto_scalarmult_base($key->privateKeyData()); |
| 263 | + $crv = $values['crv'] ?? null; |
| 264 | + assert(is_string($crv), 'Unsupported key type.'); |
| 265 | + $x = self::getPublicKey($key, $crv); |
| 266 | + if ($x !== null) { |
266 | 267 | $values['x'] = Base64UrlSafe::encodeUnpadded($x); |
267 | 268 | } |
268 | 269 |
|
269 | 270 | return $values; |
270 | 271 | } |
271 | 272 |
|
| 273 | + private static function getPublicKey(PrivateKey $key, string $crv): ?string |
| 274 | + { |
| 275 | + switch ($crv) { |
| 276 | + case 'Ed25519': |
| 277 | + return Ed25519::publickey_from_secretkey($key->privateKeyData()); |
| 278 | + case 'X25519': |
| 279 | + if (extension_loaded('sodium')) { |
| 280 | + return sodium_crypto_scalarmult_base($key->privateKeyData()); |
| 281 | + } |
| 282 | + // no break |
| 283 | + default: |
| 284 | + return null; |
| 285 | + } |
| 286 | + } |
| 287 | + |
272 | 288 | private static function checkType(string $curve): void |
273 | 289 | { |
274 | 290 | $curves = ['Ed448ph', 'Ed25519ph', 'Ed448', 'Ed25519', 'X448', 'X25519']; |
|
0 commit comments