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 2020-04-06
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         * @return The JSON object string representation.
311         */
312        @Override
313        public String toString() {
314
315                return JSONObjectUtils.toJSONString(toJSONObject());
316        }
317
318
319        /**
320         * Parses the specified string representing a JSON Web Key (JWK) set.
321         *
322         * @param s The string to parse. Must not be {@code null}.
323         *
324         * @return The JWK set.
325         *
326         * @throws ParseException If the string couldn't be parsed to a valid
327         *                        JSON Web Key (JWK) set.
328         */
329        public static JWKSet parse(final String s)
330                throws ParseException {
331
332                return parse(JSONObjectUtils.parse(s));
333        }
334
335
336        /**
337         * Parses the specified JSON object representing a JSON Web Key (JWK) 
338         * set.
339         *
340         * @param json The JSON object 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 Map<String, Object> json)
348                throws ParseException {
349
350                List<Object> keyArray = JSONObjectUtils.getJSONArray(json, "keys");
351                
352                if (keyArray == null) {
353                        throw new ParseException("Missing required \"keys\" member", 0);
354                }
355
356                List<JWK> keys = new LinkedList<>();
357
358                for (int i=0; i < keyArray.size(); i++) {
359
360                        try {
361                                Map<String, Object> keyJSONObject = (Map<String, Object>)keyArray.get(i);
362                                keys.add(JWK.parse(keyJSONObject));
363                                
364                        } catch (ClassCastException e) {
365                                
366                                throw new ParseException("The \"keys\" JSON array must contain JSON objects only", 0);
367                                
368                        } catch (ParseException e) {
369
370                                throw new ParseException("Invalid JWK at position " + i + ": " + e.getMessage(), 0);
371                        }
372                }
373
374                // Parse additional custom members
375                Map<String, Object> additionalMembers = new HashMap<>();
376                for (Map.Entry<String,Object> entry: json.entrySet()) {
377                        
378                        if (entry.getKey() == null || entry.getKey().equals("keys")) {
379                                continue;
380                        }
381                        
382                        additionalMembers.put(entry.getKey(), entry.getValue());
383                }
384                
385                return new JWKSet(keys, additionalMembers);
386        }
387
388
389        /**
390         * Loads a JSON Web Key (JWK) set from the specified input stream.
391         *
392         * @param inputStream The JWK set input stream. Must not be {@code null}.
393         *
394         * @return The JWK set.
395         *
396         * @throws IOException    If the input stream couldn't be read.
397         * @throws ParseException If the input stream couldn't be parsed to a valid
398         *                        JSON Web Key (JWK) set.
399         */
400        public static JWKSet load(final InputStream inputStream)
401                throws IOException, ParseException {
402
403                return parse(IOUtils.readInputStreamToString(inputStream, StandardCharsets.UTF_8));
404        }
405
406
407        /**
408         * Loads a JSON Web Key (JWK) set from the specified file.
409         *
410         * @param file The JWK set file. Must not be {@code null}.
411         *
412         * @return The JWK set.
413         *
414         * @throws IOException    If the file couldn't be read.
415         * @throws ParseException If the file couldn't be parsed to a valid
416         *                        JSON Web Key (JWK) set.
417         */
418        public static JWKSet load(final File file)
419                throws IOException, ParseException {
420
421                return parse(IOUtils.readFileToString(file, StandardCharsets.UTF_8));
422        }
423
424
425        /**
426         * Loads a JSON Web Key (JWK) set from the specified URL.
427         *
428         * @param url            The JWK set URL. Must not be {@code null}.
429         * @param connectTimeout The URL connection timeout, in milliseconds.
430         *                       If zero no (infinite) timeout.
431         * @param readTimeout    The URL read timeout, in milliseconds. If zero
432         *                       no (infinite) timeout.
433         * @param sizeLimit      The read size limit, in bytes. If zero no
434         *                       limit.
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 URL url,
443                                  final int connectTimeout,
444                                  final int readTimeout,
445                                  final int sizeLimit)
446                throws IOException, ParseException {
447
448                return load(url, connectTimeout, readTimeout, sizeLimit, null);
449        }
450
451
452        /**
453         * Loads a JSON Web Key (JWK) set from the specified URL.
454         *
455         * @param url            The JWK set URL. Must not be {@code null}.
456         * @param connectTimeout The URL connection timeout, in milliseconds.
457         *                       If zero no (infinite) timeout.
458         * @param readTimeout    The URL read timeout, in milliseconds. If zero
459         *                       no (infinite) timeout.
460         * @param sizeLimit      The read size limit, in bytes. If zero no
461         *                       limit.
462         * @param proxy          The optional proxy to use when opening the
463         *                       connection to retrieve the resource. If
464         *                       {@code null}, no proxy is used.
465         *
466         * @return The JWK set.
467         *
468         * @throws IOException    If the file couldn't be read.
469         * @throws ParseException If the file couldn't be parsed to a valid
470         *                        JSON Web Key (JWK) set.
471         */
472        public static JWKSet load(final URL url,
473                                  final int connectTimeout,
474                                  final int readTimeout,
475                                  final int sizeLimit,
476                                  final Proxy proxy)
477                        throws IOException, ParseException {
478
479                DefaultResourceRetriever resourceRetriever = new DefaultResourceRetriever(
480                                connectTimeout,
481                                readTimeout,
482                                sizeLimit);
483                resourceRetriever.setProxy(proxy);
484                Resource resource = resourceRetriever.retrieveResource(url);
485                return parse(resource.getContent());
486        }
487
488
489        /**
490         * Loads a JSON Web Key (JWK) set from the specified URL.
491         *
492         * @param url The JWK set URL. Must not be {@code null}.
493         *
494         * @return The JWK set.
495         *
496         * @throws IOException    If the file couldn't be read.
497         * @throws ParseException If the file couldn't be parsed to a valid
498         *                        JSON Web Key (JWK) set.
499         */
500        public static JWKSet load(final URL url)
501                throws IOException, ParseException {
502
503                return load(url, 0, 0, 0);
504        }
505        
506        
507        /**
508         * Loads a JSON Web Key (JWK) set from the specified JCA key store. Key
509         * conversion exceptions are silently swallowed. PKCS#11 stores are
510         * also supported. Requires BouncyCastle.
511         *
512         * <p><strong>Important:</strong> The X.509 certificates are not
513         * validated!
514         *
515         * @param keyStore The key store. Must not be {@code null}.
516         * @param pwLookup The password lookup for password-protected keys,
517         *                 {@code null} if not specified.
518         *
519         * @return The JWK set, empty if no keys were loaded.
520         *
521         * @throws KeyStoreException On a key store exception.
522         */
523        public static JWKSet load(final KeyStore keyStore, final PasswordLookup pwLookup)
524                throws KeyStoreException {
525                
526                List<JWK> jwks = new LinkedList<>();
527                
528                // Load RSA and EC keys
529                for (Enumeration<String> keyAliases = keyStore.aliases(); keyAliases.hasMoreElements(); ) {
530                        
531                        final String keyAlias = keyAliases.nextElement();
532                        final char[] keyPassword = pwLookup == null ? "".toCharArray() : pwLookup.lookupPassword(keyAlias);
533                        
534                        Certificate cert = keyStore.getCertificate(keyAlias);
535                        if (cert == null) {
536                                continue; // skip
537                        }
538                        
539                        if (cert.getPublicKey() instanceof RSAPublicKey) {
540                                
541                                RSAKey rsaJWK;
542                                try {
543                                        rsaJWK = RSAKey.load(keyStore, keyAlias, keyPassword);
544                                } catch (JOSEException e) {
545                                        continue; // skip cert
546                                }
547                                
548                                if (rsaJWK == null) {
549                                        continue; // skip key
550                                }
551                                
552                                jwks.add(rsaJWK);
553                                
554                        } else if (cert.getPublicKey() instanceof ECPublicKey) {
555                                
556                                ECKey ecJWK;
557                                try {
558                                        ecJWK = ECKey.load(keyStore, keyAlias, keyPassword);
559                                } catch (JOSEException e) {
560                                        continue; // skip cert
561                                }
562                                
563                                if (ecJWK != null) {
564                                        jwks.add(ecJWK);
565                                }
566                        }
567                }
568                
569                
570                // Load symmetric keys
571                for (Enumeration<String> keyAliases = keyStore.aliases(); keyAliases.hasMoreElements(); ) {
572                        
573                        final String keyAlias = keyAliases.nextElement();
574                        final char[] keyPassword = pwLookup == null ? "".toCharArray() : pwLookup.lookupPassword(keyAlias);
575                        
576                        OctetSequenceKey octJWK;
577                        try {
578                                octJWK = OctetSequenceKey.load(keyStore, keyAlias, keyPassword);
579                        } catch (JOSEException e) {
580                                continue; // skip key
581                        }
582                        
583                        if (octJWK != null) {
584                                jwks.add(octJWK);
585                        }
586                }
587                
588                return new JWKSet(jwks);
589        }
590}