aboutsummaryrefslogtreecommitdiffstats
path: root/posts/json_web_key_set.md
blob: 8fb81d4df6e0183986f78a46f5b44d8f79e801f6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
---
title: Generate a JSON Web Key Set from PHP for RSA Keys
published: 2018-08-22
---

Using PHP it is quite easy to generate a 
[JSON Web Key](https://tools.ietf.org/html/rfc7517) (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.