001/*
002 * nimbus-jose-jwt
003 *
004 * Copyright 2012-2018, Connect2id Ltd.
005 *
006 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use
007 * this file except in compliance with the License. You may obtain a copy of the
008 * License at
009 *
010 *    http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software distributed
013 * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
014 * CONDITIONS OF ANY KIND, either express or implied. See the License for the
015 * specific language governing permissions and limitations under the License.
016 */
017
018package com.nimbusds.jose.jwk;
019
020
021import java.io.File;
022import java.io.IOException;
023import java.io.InputStream;
024import java.io.Serializable;
025import java.net.Proxy;
026import java.net.URL;
027import java.nio.charset.StandardCharsets;
028import java.security.KeyStore;
029import java.security.KeyStoreException;
030import java.security.cert.Certificate;
031import java.security.interfaces.ECPublicKey;
032import java.security.interfaces.RSAPublicKey;
033import java.text.ParseException;
034import java.util.*;
035
036import net.jcip.annotations.Immutable;
037
038import com.nimbusds.jose.JOSEException;
039import com.nimbusds.jose.util.*;
040
041
042/**
043 * JSON Web Key (JWK) set. Represented by a JSON object that contains an array
044 * of {@link JWK JSON Web Keys} (JWKs) as the value of its "keys" member.
045 * Additional (custom) members of the JWK Set JSON object are also supported.
046 *
047 * <p>Example JSON Web Key (JWK) set:
048 *
049 * <pre>
050 * {
051 *   "keys" : [ { "kty" : "EC",
052 *                "crv" : "P-256",
053 *                "x"   : "MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4",
054 *                "y"   : "4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM",
055 *                "use" : "enc",
056 *                "kid" : "1" },
057 *
058 *              { "kty" : "RSA",
059 *                "n"   : "0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx
060 *                         4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMs
061 *                         tn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2
062 *                         QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbI
063 *                         SD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqb
064 *                         w0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw",
065 *                "e"   : "AQAB",
066 *                "alg" : "RS256",
067 *                "kid" : "2011-04-29" } ]
068 * }
069 * </pre>
070 *
071 * @author Vladimir Dzhuvinov
072 * @author Vedran Pavic
073 * @version 2021-02-01
074 */
075@Immutable
076public class JWKSet implements Serializable {
077        
078        
079        private static final long serialVersionUID = 1L;
080
081
082        /**
083         * The MIME type of JWK set objects: 
084         * {@code application/jwk-set+json; charset=UTF-8}
085         */
086        public static final String MIME_TYPE = "application/jwk-set+json; charset=UTF-8";
087
088
089        /**
090         * The JWK list.
091         */
092        private final List<JWK> keys;
093
094
095        /**
096         * Additional custom members.
097         */
098        private final Map<String,Object> customMembers;
099
100
101        /**
102         * Creates a new empty JSON Web Key (JWK) set.
103         */
104        public JWKSet() {
105
106                this(Collections.<JWK>emptyList());
107        }
108
109
110        /**
111         * Creates a new JSON Web Key (JWK) set with a single key.
112         *
113         * @param key The JWK. Must not be {@code null}.
114         */
115        public JWKSet(final JWK key) {
116                
117                this(Collections.singletonList(key));
118                
119                if (key == null) {
120                        throw new IllegalArgumentException("The JWK must not be null");
121                }
122        }
123
124
125        /**
126         * Creates a new JSON Web Key (JWK) set with the specified keys.
127         *
128         * @param keys The JWK list. Must not be {@code null}.
129         */
130        public JWKSet(final List<JWK> keys) {
131
132                this(keys, Collections.<String, Object>emptyMap());
133        }
134
135
136        /**
137         * Creates a new JSON Web Key (JWK) set with the specified keys and
138         * additional custom members.
139         *
140         * @param keys          The JWK list. Must not be {@code null}.
141         * @param customMembers The additional custom members. Must not be
142         *                      {@code null}.
143         */
144        public JWKSet(final List<JWK> keys, final Map<String,Object> customMembers) {
145
146                if (keys == null) {
147                        throw new IllegalArgumentException("The JWK list must not be null");
148                }
149
150                this.keys = Collections.unmodifiableList(keys);
151
152                this.customMembers = Collections.unmodifiableMap(customMembers);
153        }
154
155
156        /**
157         * Gets the keys (ordered) of this JSON Web Key (JWK) set.
158         *
159         * @return The keys, empty list if none.
160         */
161        public List<JWK> getKeys() {
162
163                return keys;
164        }
165
166        
167        /**
168         * Gets the key from this JSON Web Key (JWK) set as identified by its 
169         * Key ID (kid) member.
170         * 
171         * <p>If more than one key exists in the JWK Set with the same 
172         * identifier, this function returns only the first one in the set.
173         *
174         * @param kid They key identifier.
175         *
176         * @return The key identified by {@code kid} or {@code null} if no key 
177         *         exists.
178         */
179        public JWK getKeyByKeyId(String kid) {
180                
181                for (JWK key : getKeys()) {
182                
183                        if (key.getKeyID() != null && key.getKeyID().equals(kid)) {
184                                return key;
185                        }
186                }
187                
188                // no key found
189                return null;
190        }
191        
192        
193        /**
194         * Returns {@code true} if this JWK set contains the specified JWK as
195         * public or private key, by comparing its thumbprint with those of the
196         * keys in the set.
197         *
198         * @param jwk The JWK to check. Must not be {@code null}.
199         *
200         * @return {@code true} if contained, {@code false} if not.
201         *
202         * @throws JOSEException If thumbprint computation failed.
203         */
204        public boolean containsJWK(final JWK jwk) throws JOSEException {
205                
206                Base64URL thumbprint = jwk.computeThumbprint();
207                
208                for (JWK k: getKeys()) {
209                        if (thumbprint.equals(k.computeThumbprint())) {
210                                return true; // found
211                        }
212                }
213                return false;
214        }
215
216
217        /**
218         * Gets the additional custom members of this JSON Web Key (JWK) set.
219         *
220         * @return The additional custom members, empty map if none.
221         */
222        public Map<String,Object> getAdditionalMembers() {
223
224                return customMembers;
225        }
226
227
228        /**
229         * Returns a copy of this JSON Web Key (JWK) set with all private keys
230         * and parameters removed.
231         *
232         * @return A copy of this JWK set with all private keys and parameters
233         *         removed.
234         */
235        public JWKSet toPublicJWKSet() {
236
237                List<JWK> publicKeyList = new LinkedList<>();
238
239                for (JWK key: keys) {
240
241                        JWK publicKey = key.toPublicJWK();
242
243                        if (publicKey != null) {
244                                publicKeyList.add(publicKey);
245                        }
246                }
247
248                return new JWKSet(publicKeyList, customMembers);
249        }
250
251
252        /**
253         * Returns the JSON object representation of this JSON Web Key (JWK) 
254         * set. Private keys and parameters will be omitted from the output.
255         * Use the alternative {@link #toJSONObject(boolean)} method if you
256         * wish to include them.
257         *
258         * @return The JSON object representation.
259         */
260        public Map<String, Object> toJSONObject() {
261
262                return toJSONObject(true);
263        }
264
265
266        /**
267         * Returns the JSON object representation of this JSON Web Key (JWK) 
268         * set.
269         *
270         * @param publicKeysOnly Controls the inclusion of private keys and
271         *                       parameters into the output JWK members. If
272         *                       {@code true} private keys and parameters will
273         *                       be omitted. If {@code false} all available key
274         *                       parameters will be included.
275         *
276         * @return The JSON object representation.
277         */
278        public Map<String, Object> toJSONObject(final boolean publicKeysOnly) {
279
280                Map<String, Object> o = JSONObjectUtils.newJSONObject();
281                o.putAll(customMembers);
282                List<Object> a = JSONArrayUtils.newJSONArray();
283
284                for (JWK key: keys) {
285
286                        if (publicKeysOnly) {
287
288                                // Try to get public key, then serialise
289                                JWK publicKey = key.toPublicJWK();
290
291                                if (publicKey != null) {
292                                        a.add(publicKey.toJSONObject());
293                                }
294                        } else {
295
296                                a.add(key.toJSONObject());
297                        }
298                }
299
300                o.put("keys", a);
301
302                return o;
303        }
304
305
306        /**
307         * Returns the JSON object string representation of this JSON Web Key
308         * (JWK) set.
309         *
310         * @param publicKeysOnly Controls the inclusion of private keys and
311         *                       parameters into the output JWK members. If
312         *                       {@code true} private keys and parameters will
313         *                       be omitted. If {@code false} all available key
314         *                       parameters will be included.
315         *
316         * @return The JSON object string representation.
317         */
318        public String toString(final boolean publicKeysOnly) {
319
320                return JSONObjectUtils.toJSONString(toJSONObject(publicKeysOnly));
321        }
322
323
324        /**
325         * Returns the JSON object string representation of this JSON Web Key
326         * (JWK) set.
327         *
328         * @return The JSON object string representation.
329         */
330        @Override
331        public String toString() {
332
333                return toString(true);
334        }
335
336
337        /**
338         * Parses the specified string representing a JSON Web Key (JWK) set.
339         *
340         * @param s The string to parse. Must not be {@code null}.
341         *
342         * @return The JWK set.
343         *
344         * @throws ParseException If the string couldn't be parsed to a valid
345         *                        JSON Web Key (JWK) set.
346         */
347        public static JWKSet parse(final String s)
348                throws ParseException {
349
350                return parse(JSONObjectUtils.parse(s));
351        }
352
353
354        /**
355         * Parses the specified JSON object representing a JSON Web Key (JWK) 
356         * set.
357         *
358         * @param json The JSON object to parse. Must not be {@code null}.
359         *
360         * @return The JWK set.
361         *
362         * @throws ParseException If the string couldn't be parsed to a valid
363         *                        JSON Web Key (JWK) set.
364         */
365        public static JWKSet parse(final Map<String, Object> json)
366                throws ParseException {
367
368                List<Object> keyArray = JSONObjectUtils.getJSONArray(json, "keys");
369                
370                if (keyArray == null) {
371                        throw new ParseException("Missing required \"keys\" member", 0);
372                }
373
374                List<JWK> keys = new LinkedList<>();
375
376                for (int i=0; i < keyArray.size(); i++) {
377
378                        try {
379                                Map<String, Object> keyJSONObject = (Map<String, Object>)keyArray.get(i);
380                                keys.add(JWK.parse(keyJSONObject));
381                                
382                        } catch (ClassCastException e) {
383                                
384                                throw new ParseException("The \"keys\" JSON array must contain JSON objects only", 0);
385                                
386                        } catch (ParseException e) {
387                                
388                                if (e.getMessage() != null && e.getMessage().startsWith("Unsupported key type")) {
389                                        // Ignore unknown key type
390                                        // https://tools.ietf.org/html/rfc7517#section-5
391                                        continue;
392                                }
393
394                                throw new ParseException("Invalid JWK at position " + i + ": " + e.getMessage(), 0);
395                        }
396                }
397
398                // Parse additional custom members
399                Map<String, Object> additionalMembers = new HashMap<>();
400                for (Map.Entry<String,Object> entry: json.entrySet()) {
401                        
402                        if (entry.getKey() == null || entry.getKey().equals("keys")) {
403                                continue;
404                        }
405                        
406                        additionalMembers.put(entry.getKey(), entry.getValue());
407                }
408                
409                return new JWKSet(keys, additionalMembers);
410        }
411
412
413        /**
414         * Loads a JSON Web Key (JWK) set from the specified input stream.
415         *
416         * @param inputStream The JWK set input stream. Must not be {@code null}.
417         *
418         * @return The JWK set.
419         *
420         * @throws IOException    If the input stream couldn't be read.
421         * @throws ParseException If the input stream couldn't be parsed to a valid
422         *                        JSON Web Key (JWK) set.
423         */
424        public static JWKSet load(final InputStream inputStream)
425                throws IOException, ParseException {
426
427                return parse(IOUtils.readInputStreamToString(inputStream, StandardCharsets.UTF_8));
428        }
429
430
431        /**
432         * Loads a JSON Web Key (JWK) set from the specified file.
433         *
434         * @param file The JWK set file. Must not be {@code null}.
435         *
436         * @return The JWK set.
437         *
438         * @throws IOException    If the file couldn't be read.
439         * @throws ParseException If the file couldn't be parsed to a valid
440         *                        JSON Web Key (JWK) set.
441         */
442        public static JWKSet load(final File file)
443                throws IOException, ParseException {
444
445                return parse(IOUtils.readFileToString(file, StandardCharsets.UTF_8));
446        }
447
448
449        /**
450         * Loads a JSON Web Key (JWK) set from the specified URL.
451         *
452         * @param url            The JWK set URL. Must not be {@code null}.
453         * @param connectTimeout The URL connection timeout, in milliseconds.
454         *                       If zero no (infinite) timeout.
455         * @param readTimeout    The URL read timeout, in milliseconds. If zero
456         *                       no (infinite) timeout.
457         * @param sizeLimit      The read size limit, in bytes. If zero no
458         *                       limit.
459         *
460         * @return The JWK set.
461         *
462         * @throws IOException    If the file couldn't be read.
463         * @throws ParseException If the file couldn't be parsed to a valid
464         *                        JSON Web Key (JWK) set.
465         */
466        public static JWKSet load(final URL url,
467                                  final int connectTimeout,
468                                  final int readTimeout,
469                                  final int sizeLimit)
470                throws IOException, ParseException {
471
472                return load(url, connectTimeout, readTimeout, sizeLimit, null);
473        }
474
475
476        /**
477         * Loads a JSON Web Key (JWK) set from the specified URL.
478         *
479         * @param url            The JWK set URL. Must not be {@code null}.
480         * @param connectTimeout The URL connection timeout, in milliseconds.
481         *                       If zero no (infinite) timeout.
482         * @param readTimeout    The URL read timeout, in milliseconds. If zero
483         *                       no (infinite) timeout.
484         * @param sizeLimit      The read size limit, in bytes. If zero no
485         *                       limit.
486         * @param proxy          The optional proxy to use when opening the
487         *                       connection to retrieve the resource. If
488         *                       {@code null}, no proxy is used.
489         *
490         * @return The JWK set.
491         *
492         * @throws IOException    If the file couldn't be read.
493         * @throws ParseException If the file couldn't be parsed to a valid
494         *                        JSON Web Key (JWK) set.
495         */
496        public static JWKSet load(final URL url,
497                                  final int connectTimeout,
498                                  final int readTimeout,
499                                  final int sizeLimit,
500                                  final Proxy proxy)
501                        throws IOException, ParseException {
502
503                DefaultResourceRetriever resourceRetriever = new DefaultResourceRetriever(
504                                connectTimeout,
505                                readTimeout,
506                                sizeLimit);
507                resourceRetriever.setProxy(proxy);
508                Resource resource = resourceRetriever.retrieveResource(url);
509                return parse(resource.getContent());
510        }
511
512
513        /**
514         * Loads a JSON Web Key (JWK) set from the specified URL.
515         *
516         * @param url The JWK set URL. Must not be {@code null}.
517         *
518         * @return The JWK set.
519         *
520         * @throws IOException    If the file couldn't be read.
521         * @throws ParseException If the file couldn't be parsed to a valid
522         *                        JSON Web Key (JWK) set.
523         */
524        public static JWKSet load(final URL url)
525                throws IOException, ParseException {
526
527                return load(url, 0, 0, 0);
528        }
529        
530        
531        /**
532         * Loads a JSON Web Key (JWK) set from the specified JCA key store. Key
533         * conversion exceptions are silently swallowed. PKCS#11 stores are
534         * also supported. Requires BouncyCastle.
535         *
536         * <p><strong>Important:</strong> The X.509 certificates are not
537         * validated!
538         *
539         * @param keyStore The key store. Must not be {@code null}.
540         * @param pwLookup The password lookup for password-protected keys,
541         *                 {@code null} if not specified.
542         *
543         * @return The JWK set, empty if no keys were loaded.
544         *
545         * @throws KeyStoreException On a key store exception.
546         */
547        public static JWKSet load(final KeyStore keyStore, final PasswordLookup pwLookup)
548                throws KeyStoreException {
549                
550                List<JWK> jwks = new LinkedList<>();
551                
552                // Load RSA and EC keys
553                for (Enumeration<String> keyAliases = keyStore.aliases(); keyAliases.hasMoreElements(); ) {
554                        
555                        final String keyAlias = keyAliases.nextElement();
556                        final char[] keyPassword = pwLookup == null ? "".toCharArray() : pwLookup.lookupPassword(keyAlias);
557                        
558                        Certificate cert = keyStore.getCertificate(keyAlias);
559                        if (cert == null) {
560                                continue; // skip
561                        }
562                        
563                        if (cert.getPublicKey() instanceof RSAPublicKey) {
564                                
565                                RSAKey rsaJWK;
566                                try {
567                                        rsaJWK = RSAKey.load(keyStore, keyAlias, keyPassword);
568                                } catch (JOSEException e) {
569                                        continue; // skip cert
570                                }
571                                
572                                if (rsaJWK == null) {
573                                        continue; // skip key
574                                }
575                                
576                                jwks.add(rsaJWK);
577                                
578                        } else if (cert.getPublicKey() instanceof ECPublicKey) {
579                                
580                                ECKey ecJWK;
581                                try {
582                                        ecJWK = ECKey.load(keyStore, keyAlias, keyPassword);
583                                } catch (JOSEException e) {
584                                        continue; // skip cert
585                                }
586                                
587                                if (ecJWK != null) {
588                                        jwks.add(ecJWK);
589                                }
590                        }
591                }
592                
593                
594                // Load symmetric keys
595                for (Enumeration<String> keyAliases = keyStore.aliases(); keyAliases.hasMoreElements(); ) {
596                        
597                        final String keyAlias = keyAliases.nextElement();
598                        final char[] keyPassword = pwLookup == null ? "".toCharArray() : pwLookup.lookupPassword(keyAlias);
599                        
600                        OctetSequenceKey octJWK;
601                        try {
602                                octJWK = OctetSequenceKey.load(keyStore, keyAlias, keyPassword);
603                        } catch (JOSEException e) {
604                                continue; // skip key
605                        }
606                        
607                        if (octJWK != null) {
608                                jwks.add(octJWK);
609                        }
610                }
611                
612                return new JWKSet(jwks);
613        }
614}