/**
* @param string $pem
* @param null|string $password
*
* @throws \Exception
*
* @return array
*/
private static function loadKeyFromPEM($pem, $password = null)
{
if (preg_match('#DEK-Info: (.+),(.+)#', $pem, $matches)) {
$pem = self::decodePem($pem, $matches, $password);
}
self::sanitizePEM($pem);
$res = openssl_pkey_get_private($pem);
if ($res === false) {
$res = openssl_pkey_get_public($pem);
}
Assertion::false($res === false, 'Unable to load the key');
$details = openssl_pkey_get_details($res);
Assertion::isArray($details, 'Unable to get details of the key');
Assertion::keyExists($details, 'type', 'Unable to get details of the key');
switch ($details['type']) {
case OPENSSL_KEYTYPE_EC:
$ec_key = new ECKey($pem);
return $ec_key->toArray();
case OPENSSL_KEYTYPE_RSA:
$rsa_key = new RSAKey($pem);
return $rsa_key->toArray();
default:
throw new \InvalidArgumentException('Unsupported key type');
}
}