| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
namespace Jose\Component\KeyManagement\KeyConverter; |
| 6 |
|
| 7 |
use Brick\Math\BigInteger; |
| 8 |
use InvalidArgumentException; |
| 9 |
use Jose\Component\Core\Util\Base64UrlSafe; |
| 10 |
use OpenSSLCertificate; |
| 11 |
use ParagonIE\Sodium\Core\Ed25519; |
| 12 |
use RuntimeException; |
| 13 |
use SpomkyLabs\Pki\CryptoEncoding\PEM; |
| 14 |
use SpomkyLabs\Pki\CryptoTypes\AlgorithmIdentifier\AlgorithmIdentifier; |
| 15 |
use SpomkyLabs\Pki\CryptoTypes\Asymmetric\PrivateKey; |
| 16 |
use SpomkyLabs\Pki\CryptoTypes\Asymmetric\PublicKey; |
| 17 |
use SpomkyLabs\Pki\CryptoTypes\Asymmetric\RSA\RSASSAPSSPrivateKey; |
| 18 |
use Throwable; |
| 19 |
use function array_key_exists; |
| 20 |
use function assert; |
| 21 |
use function count; |
| 22 |
use function extension_loaded; |
| 23 |
use function in_array; |
| 24 |
use function is_array; |
| 25 |
use function is_string; |
| 26 |
use const E_ERROR; |
| 27 |
use const E_PARSE; |
| 28 |
use const OPENSSL_KEYTYPE_EC; |
| 29 |
use const OPENSSL_KEYTYPE_RSA; |
| 30 |
use const OPENSSL_RAW_DATA; |
| 31 |
use const PREG_PATTERN_ORDER; |
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
final class KeyConverter |
| 37 |
{ |
| 38 |
public static function loadKeyFromCertificateFile(string $file): array |
| 39 |
{ |
| 40 |
if (! file_exists($file)) { |
| 41 |
throw new InvalidArgumentException(sprintf('File "%s" does not exist.', $file)); |
| 42 |
} |
| 43 |
$content = file_get_contents($file); |
| 44 |
if (! is_string($content)) { |
| 45 |
throw new InvalidArgumentException(sprintf('File "%s" cannot be read.', $file)); |
| 46 |
} |
| 47 |
|
| 48 |
return self::loadKeyFromCertificate($content); |
| 49 |
} |
| 50 |
|
| 51 |
public static function loadKeyFromCertificate(string $certificate): array |
| 52 |
{ |
| 53 |
if (! extension_loaded('openssl')) { |
| 54 |
throw new RuntimeException('Please install the OpenSSL extension'); |
| 55 |
} |
| 56 |
|
| 57 |
$errorReporting = error_reporting(E_ERROR | E_PARSE); |
| 58 |
try { |
| 59 |
$res = openssl_x509_read($certificate); |
| 60 |
if ($res === false) { |
| 61 |
throw new InvalidArgumentException('Unable to load the certificate.'); |
| 62 |
} |
| 63 |
} catch (Throwable) { |
| 64 |
$certificate = self::convertDerToPem($certificate); |
| 65 |
$res = openssl_x509_read($certificate); |
| 66 |
} finally { |
| 67 |
error_reporting($errorReporting); |
| 68 |
} |
| 69 |
if ($res === false) { |
| 70 |
throw new InvalidArgumentException('Unable to load the certificate.'); |
| 71 |
} |
| 72 |
|
| 73 |
return self::loadKeyFromX509Resource($res); |
| 74 |
} |
| 75 |
|
| 76 |
public static function loadKeyFromX509Resource(OpenSSLCertificate $res): array |
| 77 |
{ |
| 78 |
if (! extension_loaded('openssl')) { |
| 79 |
throw new RuntimeException('Please install the OpenSSL extension'); |
| 80 |
} |
| 81 |
$key = openssl_pkey_get_public($res); |
| 82 |
if ($key === false) { |
| 83 |
throw new InvalidArgumentException('Unable to load the certificate.'); |
| 84 |
} |
| 85 |
$details = openssl_pkey_get_details($key); |
| 86 |
if (! is_array($details)) { |
| 87 |
throw new InvalidArgumentException('Unable to load the certificate'); |
| 88 |
} |
| 89 |
if (isset($details['key'])) { |
| 90 |
$values = self::loadKeyFromPEM($details['key']); |
| 91 |
openssl_x509_export($res, $out); |
| 92 |
$x5c = preg_replace('#-.*-#', '', (string) $out); |
| 93 |
$x5c = preg_replace('~\R~', '', (string) $x5c); |
| 94 |
if (! is_string($x5c)) { |
| 95 |
throw new InvalidArgumentException('Unable to load the certificate'); |
| 96 |
} |
| 97 |
$x5c = trim($x5c); |
| 98 |
|
| 99 |
$x5tsha1 = openssl_x509_fingerprint($res, 'sha1', true); |
| 100 |
$x5tsha256 = openssl_x509_fingerprint($res, 'sha256', true); |
| 101 |
if (! is_string($x5tsha1) || ! is_string($x5tsha256)) { |
| 102 |
throw new InvalidArgumentException('Unable to compute the certificate fingerprint'); |
| 103 |
} |
| 104 |
|
| 105 |
$values['x5c'] = [$x5c]; |
| 106 |
$values['x5t'] = Base64UrlSafe::encodeUnpadded($x5tsha1); |
| 107 |
$values['x5t#256'] = Base64UrlSafe::encodeUnpadded($x5tsha256); |
| 108 |
|
| 109 |
return $values; |
| 110 |
} |
| 111 |
|
| 112 |
throw new InvalidArgumentException('Unable to load the certificate'); |
| 113 |
} |
| 114 |
|
| 115 |
public static function loadFromKeyFile(string $file, ?string $password = null): array |
| 116 |
{ |
| 117 |
$content = file_get_contents($file); |
| 118 |
if (! is_string($content)) { |
| 119 |
throw new InvalidArgumentException('Unable to load the key from the file.'); |
| 120 |
} |
| 121 |
|
| 122 |
return self::loadFromKey($content, $password); |
| 123 |
} |
| 124 |
|
| 125 |
public static function loadFromKey(string $key, ?string $password = null): array |
| 126 |
{ |
| 127 |
try { |
| 128 |
return self::loadKeyFromDER($key, $password); |
| 129 |
} catch (Throwable) { |
| 130 |
return self::loadKeyFromPEM($key, $password); |
| 131 |
} |
| 132 |
} |
| 133 |
|
| 134 |
|
| 135 |
|
| 136 |
|
| 137 |
|
| 138 |
public static function loadFromX5C(array $x5c): array |
| 139 |
{ |
| 140 |
if (! extension_loaded('openssl')) { |
| 141 |
throw new RuntimeException('Please install the OpenSSL extension'); |
| 142 |
} |
| 143 |
if (count($x5c) === 0) { |
| 144 |
throw new InvalidArgumentException('The certificate chain is empty'); |
| 145 |
} |
| 146 |
foreach ($x5c as $id => $cert) { |
| 147 |
$x5c[$id] = '-----BEGIN CERTIFICATE-----' . "\n" . chunk_split( |
| 148 |
(string) $cert, |
| 149 |
64, |
| 150 |
"\n" |
| 151 |
) . '-----END CERTIFICATE-----'; |
| 152 |
$x509 = openssl_x509_read($x5c[$id]); |
| 153 |
if ($x509 === false) { |
| 154 |
throw new InvalidArgumentException('Unable to load the certificate chain'); |
| 155 |
} |
| 156 |
$parsed = openssl_x509_parse($x509); |
| 157 |
if ($parsed === false) { |
| 158 |
throw new InvalidArgumentException('Unable to load the certificate chain'); |
| 159 |
} |
| 160 |
} |
| 161 |
|
| 162 |
return self::loadKeyFromCertificate(reset($x5c)); |
| 163 |
} |
| 164 |
|
| 165 |
private static function loadKeyFromDER(string $der, ?string $password = null): array |
| 166 |
{ |
| 167 |
$pem = self::convertDerToPem($der); |
| 168 |
|
| 169 |
return self::loadKeyFromPEM($pem, $password); |
| 170 |
} |
| 171 |
|
| 172 |
private static function loadKeyFromPEM(string $pem, ?string $password = null): array |
| 173 |
{ |
| 174 |
if (! extension_loaded('openssl')) { |
| 175 |
throw new RuntimeException('Please install the OpenSSL extension'); |
| 176 |
} |
| 177 |
|
| 178 |
if (preg_match('#DEK-Info: (.+),(.+)#', $pem, $matches) === 1) { |
| 179 |
$pem = self::decodePem($pem, $matches, $password); |
| 180 |
} |
| 181 |
|
| 182 |
if (preg_match('#BEGIN ENCRYPTED PRIVATE KEY(.+)(.+)#', $pem) === 1) { |
| 183 |
$decrypted = openssl_pkey_get_private($pem, $password); |
| 184 |
if ($decrypted === false) { |
| 185 |
throw new InvalidArgumentException('Unable to decrypt the key.'); |
| 186 |
} |
| 187 |
openssl_pkey_export($decrypted, $pem); |
| 188 |
} |
| 189 |
|
| 190 |
self::sanitizePEM($pem); |
| 191 |
$res = openssl_pkey_get_private($pem); |
| 192 |
if ($res === false) { |
| 193 |
$res = openssl_pkey_get_public($pem); |
| 194 |
} |
| 195 |
if ($res === false) { |
| 196 |
throw new InvalidArgumentException('Unable to load the key.'); |
| 197 |
} |
| 198 |
|
| 199 |
$details = openssl_pkey_get_details($res); |
| 200 |
if (! is_array($details) || ! array_key_exists('type', $details)) { |
| 201 |
throw new InvalidArgumentException('Unable to get details of the key'); |
| 202 |
} |
| 203 |
|
| 204 |
return match ($details['type']) { |
| 205 |
OPENSSL_KEYTYPE_EC => self::tryToLoadECKey($pem), |
| 206 |
OPENSSL_KEYTYPE_RSA => RSAKey::createFromPEM($pem)->toArray(), |
| 207 |
-1 => self::tryToLoadOtherKeyTypes($pem), |
| 208 |
default => throw new InvalidArgumentException('Unsupported key type'), |
| 209 |
}; |
| 210 |
} |
| 211 |
|
| 212 |
|
| 213 |
|
| 214 |
|
| 215 |
private static function tryToLoadECKey(string $input): array |
| 216 |
{ |
| 217 |
try { |
| 218 |
return ECKey::createFromPEM($input)->toArray(); |
| 219 |
} catch (Throwable) { |
| 220 |
} |
| 221 |
try { |
| 222 |
return self::tryToLoadOtherKeyTypes($input); |
| 223 |
} catch (Throwable) { |
| 224 |
} |
| 225 |
throw new InvalidArgumentException('Unable to load the key.'); |
| 226 |
} |
| 227 |
|
| 228 |
|
| 229 |
|
| 230 |
|
| 231 |
private static function tryToLoadOtherKeyTypes(string $input): array |
| 232 |
{ |
| 233 |
$pem = PEM::fromString($input); |
| 234 |
return match ($pem->type()) { |
| 235 |
PEM::TYPE_PUBLIC_KEY => self::loadPublicKey($pem), |
| 236 |
PEM::TYPE_PRIVATE_KEY => self::loadPrivateKey($pem), |
| 237 |
default => throw new InvalidArgumentException('Unsupported key type'), |
| 238 |
}; |
| 239 |
} |
| 240 |
|
| 241 |
|
| 242 |
|
| 243 |
|
| 244 |
private static function loadPrivateKey(PEM $pem): array |
| 245 |
{ |
| 246 |
try { |
| 247 |
$key = PrivateKey::fromPEM($pem); |
| 248 |
switch ($key->algorithmIdentifier()->oid()) { |
| 249 |
case AlgorithmIdentifier::OID_RSASSA_PSS_ENCRYPTION: |
| 250 |
assert($key instanceof RSASSAPSSPrivateKey); |
| 251 |
return [ |
| 252 |
'kty' => 'RSA', |
| 253 |
'n' => self::convertDecimalToBas64Url($key->modulus()), |
| 254 |
'e' => self::convertDecimalToBas64Url($key->publicExponent()), |
| 255 |
'd' => self::convertDecimalToBas64Url($key->privateExponent()), |
| 256 |
'dp' => self::convertDecimalToBas64Url($key->exponent1()), |
| 257 |
'dq' => self::convertDecimalToBas64Url($key->exponent2()), |
| 258 |
'p' => self::convertDecimalToBas64Url($key->prime1()), |
| 259 |
'q' => self::convertDecimalToBas64Url($key->prime2()), |
| 260 |
'qi' => self::convertDecimalToBas64Url($key->coefficient()), |
| 261 |
]; |
| 262 |
case AlgorithmIdentifier::OID_ED25519: |
| 263 |
case AlgorithmIdentifier::OID_ED448: |
| 264 |
case AlgorithmIdentifier::OID_X25519: |
| 265 |
case AlgorithmIdentifier::OID_X448: |
| 266 |
$curve = self::getCurve($key->algorithmIdentifier()->oid()); |
| 267 |
$values = [ |
| 268 |
'kty' => 'OKP', |
| 269 |
'crv' => $curve, |
| 270 |
'd' => Base64UrlSafe::encodeUnpadded($key->privateKeyData()), |
| 271 |
]; |
| 272 |
return self::populatePoints($key, $values); |
| 273 |
default: |
| 274 |
throw new InvalidArgumentException('Unsupported key type'); |
| 275 |
} |
| 276 |
} catch (Throwable $e) { |
| 277 |
throw new InvalidArgumentException('Unable to load the key.', 0, $e); |
| 278 |
} |
| 279 |
} |
| 280 |
|
| 281 |
|
| 282 |
|
| 283 |
|
| 284 |
private static function loadPublicKey(PEM $pem): array |
| 285 |
{ |
| 286 |
$key = PublicKey::fromPEM($pem); |
| 287 |
switch ($key->algorithmIdentifier()->oid()) { |
| 288 |
case AlgorithmIdentifier::OID_ED25519: |
| 289 |
case AlgorithmIdentifier::OID_ED448: |
| 290 |
case AlgorithmIdentifier::OID_X25519: |
| 291 |
case AlgorithmIdentifier::OID_X448: |
| 292 |
$curve = self::getCurve($key->algorithmIdentifier()->oid()); |
| 293 |
self::checkType($curve); |
| 294 |
return [ |
| 295 |
'kty' => 'OKP', |
| 296 |
'crv' => $curve, |
| 297 |
'x' => Base64UrlSafe::encodeUnpadded((string) $key->subjectPublicKey()), |
| 298 |
]; |
| 299 |
default: |
| 300 |
throw new InvalidArgumentException('Unsupported key type'); |
| 301 |
} |
| 302 |
} |
| 303 |
|
| 304 |
private static function convertDecimalToBas64Url(string $decimal): string |
| 305 |
{ |
| 306 |
return Base64UrlSafe::encodeUnpadded(BigInteger::fromBase($decimal, 10)->toBytes()); |
| 307 |
} |
| 308 |
|
| 309 |
|
| 310 |
|
| 311 |
|
| 312 |
|
| 313 |
private static function populatePoints(PrivateKey $key, array $values): array |
| 314 |
{ |
| 315 |
$crv = $values['crv'] ?? null; |
| 316 |
assert(is_string($crv), 'Unsupported key type.'); |
| 317 |
$x = self::getPublicKey($key, $crv); |
| 318 |
if ($x !== null) { |
| 319 |
$values['x'] = Base64UrlSafe::encodeUnpadded($x); |
| 320 |
} |
| 321 |
|
| 322 |
return $values; |
| 323 |
} |
| 324 |
|
| 325 |
private static function getPublicKey(PrivateKey $key, string $crv): ?string |
| 326 |
{ |
| 327 |
switch ($crv) { |
| 328 |
case 'Ed25519': |
| 329 |
return Ed25519::publickey_from_secretkey($key->privateKeyData()); |
| 330 |
case 'X25519': |
| 331 |
if (extension_loaded('sodium')) { |
| 332 |
return sodium_crypto_scalarmult_base($key->privateKeyData()); |
| 333 |
} |
| 334 |
|
| 335 |
default: |
| 336 |
return null; |
| 337 |
} |
| 338 |
} |
| 339 |
|
| 340 |
private static function checkType(string $curve): void |
| 341 |
{ |
| 342 |
$curves = ['Ed448ph', 'Ed25519ph', 'Ed448', 'Ed25519', 'X448', 'X25519']; |
| 343 |
in_array($curve, $curves, true) || throw new InvalidArgumentException('Unsupported key type.'); |
| 344 |
} |
| 345 |
|
| 346 |
|
| 347 |
|
| 348 |
|
| 349 |
private static function getCurve(string $oid): string |
| 350 |
{ |
| 351 |
return match ($oid) { |
| 352 |
'1.3.101.115' => 'Ed448ph', |
| 353 |
'1.3.101.114' => 'Ed25519ph', |
| 354 |
'1.3.101.113' => 'Ed448', |
| 355 |
'1.3.101.112' => 'Ed25519', |
| 356 |
'1.3.101.111' => 'X448', |
| 357 |
'1.3.101.110' => 'X25519', |
| 358 |
default => throw new InvalidArgumentException('Unsupported key type.'), |
| 359 |
}; |
| 360 |
} |
| 361 |
|
| 362 |
|
| 363 |
|
| 364 |
|
| 365 |
private static function sanitizePEM(string &$pem): void |
| 366 |
{ |
| 367 |
$number = preg_match_all('#(-.*-)#', $pem, $matches, PREG_PATTERN_ORDER); |
| 368 |
if ($number !== 2) { |
| 369 |
throw new InvalidArgumentException('Unable to load the key'); |
| 370 |
} |
| 371 |
|
| 372 |
$ciphertext = preg_replace('#-.*-|\r|\n| #', '', $pem); |
| 373 |
|
| 374 |
$pem = $matches[0][0] . "\n"; |
| 375 |
$pem .= chunk_split($ciphertext ?? '', 64, "\n"); |
| 376 |
$pem .= $matches[0][1] . "\n"; |
| 377 |
} |
| 378 |
|
| 379 |
|
| 380 |
|
| 381 |
|
| 382 |
private static function decodePem(string $pem, array $matches, ?string $password = null): string |
| 383 |
{ |
| 384 |
if ($password === null) { |
| 385 |
throw new InvalidArgumentException('Password required for encrypted keys.'); |
| 386 |
} |
| 387 |
|
| 388 |
$iv = pack('H*', trim($matches[2])); |
| 389 |
$iv_sub = mb_substr($iv, 0, 8, '8bit'); |
| 390 |
$symkey = pack('H*', md5($password . $iv_sub)); |
| 391 |
$symkey .= pack('H*', md5($symkey . $password . $iv_sub)); |
| 392 |
$key = preg_replace('#^(?:Proc-Type|DEK-Info): .*#m', '', $pem); |
| 393 |
$ciphertext = base64_decode(preg_replace('#-.*-|\r|\n#', '', $key ?? '') ?? '', true); |
| 394 |
if (! is_string($ciphertext)) { |
| 395 |
throw new InvalidArgumentException('Unable to encode the data.'); |
| 396 |
} |
| 397 |
|
| 398 |
$decoded = openssl_decrypt($ciphertext, mb_strtolower($matches[1]), $symkey, OPENSSL_RAW_DATA, $iv); |
| 399 |
if ($decoded === false) { |
| 400 |
throw new RuntimeException('Unable to decrypt the key'); |
| 401 |
} |
| 402 |
$number = preg_match_all('#-{5}.*-{5}#', $pem, $result); |
| 403 |
if ($number !== 2) { |
| 404 |
throw new InvalidArgumentException('Unable to load the key'); |
| 405 |
} |
| 406 |
|
| 407 |
$pem = $result[0][0] . "\n"; |
| 408 |
$pem .= chunk_split(base64_encode($decoded), 64); |
| 409 |
|
| 410 |
return $pem . ($result[0][1] . "\n"); |
| 411 |
} |
| 412 |
|
| 413 |
private static function convertDerToPem(string $der_data): string |
| 414 |
{ |
| 415 |
$pem = chunk_split(base64_encode($der_data), 64, "\n"); |
| 416 |
|
| 417 |
return '-----BEGIN CERTIFICATE-----' . "\n" . $pem . '-----END CERTIFICATE-----' . "\n"; |
| 418 |
} |
| 419 |
} |