François' Blog

Generate a JSON Web Key Set from PHP for RSA Keys

2018-08-22

Using PHP it is quite easy to generate a JSON Web Key (Set) from a PEM encoded (RSA) Public Key.

Say, you have this public key:

-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsWF+1o9XpJmqwHkBdqOe
ToHkPOsRW7JYkuEvjVLpRJLe6BKUh4tjABIaSbkvpQIudEXPmPwAbseSo5GZY9uQ
voVVmC0Fizu61ETcZyvYV+575+45A1Ua4zbrdOtHdgo4X529yYu43HQobPRX9514
FHE7DZA01Jal9rcwVQRefsbaa8i16WGVSc1tDa+/Qbb9UOXTHCM/2HK7lUH+5//6
7syfE9qnLn8JjfhksJj62A9+RObW1aFWflOx7hkNhdh4YngeVxc+RT+uebVIS11b
zYKZflvTNf6fh4LsTUb1UamPDIRZmODz/q/zudZJ/6mrXgwvpVsfQQu8VEk5w6/Q
5QIDAQAB
-----END PUBLIC KEY-----

You can convert it using the following script:

<?php

$keyInfo = openssl_pkey_get_details(openssl_pkey_get_public(file_get_contents('jwt.pub')));

$jsonData = [
    'keys' => [
        [
            'kty' => 'RSA',
            'n' => rtrim(str_replace(['+', '/'], ['-', '_'], base64_encode($keyInfo['rsa']['n'])), '='),
            'e' => rtrim(str_replace(['+', '/'], ['-', '_'], base64_encode($keyInfo['rsa']['e'])), '='),
        ],
    ],
];

echo json_encode($jsonData, JSON_PRETTY_PRINT).PHP_EOL;

This results in:

{
    "keys": [
        {
            "kty": "RSA",
            "n": "sWF-1o9XpJmqwHkBdqOeToHkPOsRW7JYkuEvjVLpRJLe6BKUh4tjABIaSbkvpQIudEXPmPwAbseSo5GZY9uQvoVVmC0Fizu61ETcZyvYV-575-45A1Ua4zbrdOtHdgo4X529yYu43HQobPRX9514FHE7DZA01Jal9rcwVQRefsbaa8i16WGVSc1tDa-_Qbb9UOXTHCM_2HK7lUH-5__67syfE9qnLn8JjfhksJj62A9-RObW1aFWflOx7hkNhdh4YngeVxc-RT-uebVIS11bzYKZflvTNf6fh4LsTUb1UamPDIRZmODz_q_zudZJ_6mrXgwvpVsfQQu8VEk5w6_Q5Q",
            "e": "AQAB"
        }
    ]
}

You can use this if you need to publish a JWK Set, e.g. when you want to run an OpenID Connect Provider.

Return to Index