Skip to content

Instantly share code, notes, and snippets.

@sicet7
Last active September 6, 2023 16:29
Show Gist options
  • Save sicet7/115bfe433e9f6f68d892c5966ed33ebb to your computer and use it in GitHub Desktop.
Save sicet7/115bfe433e9f6f68d892c5966ed33ebb to your computer and use it in GitHub Desktop.

Revisions

  1. sicet7 revised this gist Jul 4, 2023. No changes.
  2. sicet7 created this gist Jul 4, 2023.
    60 changes: 60 additions & 0 deletions jwk_with_phpseclib_test.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,60 @@
    <?php

    //REQUIREMENTS!
    //"phpseclib/phpseclib": "^3.0"
    //"lcobucci/jwt": "^5.0"
    require_once __DIR__ . '/vendor/autoload.php';

    $json = '{
    "keys": [
    {
    "kid":"my key id",
    "nbf":1493763266,
    "use":"sig",
    "kty":"RSA",
    "e":"something something JWK stuff",
    "n":"something something JWK stuff"
    }
    ]
    }';

    function getKeyFromJwkJson(string $kid, string $jwkKeySet): ?\Lcobucci\JWT\Signer\Key
    {
    $data = json_decode($jwkKeySet, true, 512, JSON_THROW_ON_ERROR);
    if (
    !is_array($data) ||
    !array_key_exists('keys', $data) ||
    !is_array($data['keys']) ||
    empty($data['keys'])
    ) {
    return null;
    }
    foreach ($data['keys'] as $key) {
    //TODO: handle nbf on keys
    if (($key['kid'] ?? '') == $kid) {
    $publicKey = \phpseclib3\Crypt\PublicKeyLoader::load(
    \phpseclib3\Crypt\RSA\Formats\Keys\JWK::load(
    json_encode($key, JSON_THROW_ON_ERROR)
    )
    );
    return \Lcobucci\JWT\Signer\Key\InMemory::plainText(
    $publicKey->toString('pkcs8')
    );
    }
    }
    return null;
    }

    $key = getKeyFromJwkJson('my key id', $json);

    if ($key === null) {
    //no key found
    exit(1);
    }

    $constraints = [
    new \Lcobucci\JWT\Validation\Constraint\SignedWith(
    new \Lcobucci\JWT\Signer\Rsa\Sha256(),
    $key
    ),
    ];