Last active
November 4, 2021 16:49
-
-
Save kmuenkel/37ead59ff01f56ee881744c11360b00c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Using 'gree/jose', 'phpseclib\Crypt', and 'guzzlehttp/guzzle' | |
if (!function_exists('is_rsa')) { | |
/** | |
* @param string $publicKey | |
* @return bool | |
*/ | |
function is_rsa(string $publicKey) | |
{ | |
return app(RSA::class)->loadKey($publicKey); | |
} | |
} | |
if (!function_exists('pem_to_jwk')) { | |
/** | |
* @param string $publicKey | |
* @param string $keyId | |
* @param string $algorithm | |
* @return string[] | |
* @throws JOSE_Exception_UnexpectedAlgorithm | |
*/ | |
function pem_to_jwk(string $publicKey, string $keyId, string $algorithm = 'RS256'): array | |
{ | |
$rsa = app(RSA::class); | |
$rsa->loadKey($publicKey); | |
$options = ['alg' => $algorithm, 'kid' => $keyId]; | |
if (!is_rsa($publicKey)) { | |
throw new UnexpectedValueException('The given value is not an RSA public key.'); | |
} | |
return JOSE_JWK::encode($rsa, $options)->components; | |
} | |
} | |
if (!function_exists('jwk_to_pem')) { | |
/** | |
* @param string[] $jwk | |
* @return string | |
*/ | |
function jwk_to_pem(array $jwk): string | |
{ | |
$rsa = JOSE_JWK::decode($jwk); | |
return (string)$rsa; | |
} | |
} | |
if (!function_exists('jwks_to_pems')) { | |
/** | |
* @param string[][] $jwks | |
* @return string[] | |
*/ | |
function jwks_to_pems(array $jwks): array | |
{ | |
$jwks = array_column($jwks['keys'] ?? $jwks, null, 'kid'); | |
return array_map('Lti\jwk_to_pem', $jwks); | |
} | |
} | |
if (!function_exists('get_jwks')) { | |
/** | |
* @param string $uri | |
* @return string[] | |
* @throws GuzzleException | |
*/ | |
function get_pems(string $uri): array | |
{ | |
$response = app(Client::class)->request('GET', $uri); | |
$body = (string)$response->getBody(); | |
$json = json_decode($body, true); | |
return jwks_to_pems($json); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment