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