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