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 if (e.getMessage() != null && e.getMessage().startsWith("Unsupported key type")) { 371 // Ignore unknown key type 372 // https://tools.ietf.org/html/rfc7517#section-5 373 continue; 374 } 375 376 throw new ParseException("Invalid JWK at position " + i + ": " + e.getMessage(), 0); 377 } 378 } 379 380 // Parse additional custom members 381 Map<String, Object> additionalMembers = new HashMap<>(); 382 for (Map.Entry<String,Object> entry: json.entrySet()) { 383 384 if (entry.getKey() == null || entry.getKey().equals("keys")) { 385 continue; 386 } 387 388 additionalMembers.put(entry.getKey(), entry.getValue()); 389 } 390 391 return new JWKSet(keys, additionalMembers); 392 } 393 394 395 /** 396 * Loads a JSON Web Key (JWK) set from the specified input stream. 397 * 398 * @param inputStream The JWK set input stream. Must not be {@code null}. 399 * 400 * @return The JWK set. 401 * 402 * @throws IOException If the input stream couldn't be read. 403 * @throws ParseException If the input stream couldn't be parsed to a valid 404 * JSON Web Key (JWK) set. 405 */ 406 public static JWKSet load(final InputStream inputStream) 407 throws IOException, ParseException { 408 409 return parse(IOUtils.readInputStreamToString(inputStream, StandardCharsets.UTF_8)); 410 } 411 412 413 /** 414 * Loads a JSON Web Key (JWK) set from the specified file. 415 * 416 * @param file The JWK set file. Must not be {@code null}. 417 * 418 * @return The JWK set. 419 * 420 * @throws IOException If the file couldn't be read. 421 * @throws ParseException If the file couldn't be parsed to a valid 422 * JSON Web Key (JWK) set. 423 */ 424 public static JWKSet load(final File file) 425 throws IOException, ParseException { 426 427 return parse(IOUtils.readFileToString(file, StandardCharsets.UTF_8)); 428 } 429 430 431 /** 432 * Loads a JSON Web Key (JWK) set from the specified URL. 433 * 434 * @param url The JWK set URL. Must not be {@code null}. 435 * @param connectTimeout The URL connection timeout, in milliseconds. 436 * If zero no (infinite) timeout. 437 * @param readTimeout The URL read timeout, in milliseconds. If zero 438 * no (infinite) timeout. 439 * @param sizeLimit The read size limit, in bytes. If zero no 440 * limit. 441 * 442 * @return The JWK set. 443 * 444 * @throws IOException If the file couldn't be read. 445 * @throws ParseException If the file couldn't be parsed to a valid 446 * JSON Web Key (JWK) set. 447 */ 448 public static JWKSet load(final URL url, 449 final int connectTimeout, 450 final int readTimeout, 451 final int sizeLimit) 452 throws IOException, ParseException { 453 454 return load(url, connectTimeout, readTimeout, sizeLimit, null); 455 } 456 457 458 /** 459 * Loads a JSON Web Key (JWK) set from the specified URL. 460 * 461 * @param url The JWK set URL. Must not be {@code null}. 462 * @param connectTimeout The URL connection timeout, in milliseconds. 463 * If zero no (infinite) timeout. 464 * @param readTimeout The URL read timeout, in milliseconds. If zero 465 * no (infinite) timeout. 466 * @param sizeLimit The read size limit, in bytes. If zero no 467 * limit. 468 * @param proxy The optional proxy to use when opening the 469 * connection to retrieve the resource. If 470 * {@code null}, no proxy is used. 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 final int connectTimeout, 480 final int readTimeout, 481 final int sizeLimit, 482 final Proxy proxy) 483 throws IOException, ParseException { 484 485 DefaultResourceRetriever resourceRetriever = new DefaultResourceRetriever( 486 connectTimeout, 487 readTimeout, 488 sizeLimit); 489 resourceRetriever.setProxy(proxy); 490 Resource resource = resourceRetriever.retrieveResource(url); 491 return parse(resource.getContent()); 492 } 493 494 495 /** 496 * Loads a JSON Web Key (JWK) set from the specified URL. 497 * 498 * @param url The JWK set URL. Must not be {@code null}. 499 * 500 * @return The JWK set. 501 * 502 * @throws IOException If the file couldn't be read. 503 * @throws ParseException If the file couldn't be parsed to a valid 504 * JSON Web Key (JWK) set. 505 */ 506 public static JWKSet load(final URL url) 507 throws IOException, ParseException { 508 509 return load(url, 0, 0, 0); 510 } 511 512 513 /** 514 * Loads a JSON Web Key (JWK) set from the specified JCA key store. Key 515 * conversion exceptions are silently swallowed. PKCS#11 stores are 516 * also supported. Requires BouncyCastle. 517 * 518 * <p><strong>Important:</strong> The X.509 certificates are not 519 * validated! 520 * 521 * @param keyStore The key store. Must not be {@code null}. 522 * @param pwLookup The password lookup for password-protected keys, 523 * {@code null} if not specified. 524 * 525 * @return The JWK set, empty if no keys were loaded. 526 * 527 * @throws KeyStoreException On a key store exception. 528 */ 529 public static JWKSet load(final KeyStore keyStore, final PasswordLookup pwLookup) 530 throws KeyStoreException { 531 532 List<JWK> jwks = new LinkedList<>(); 533 534 // Load RSA and EC keys 535 for (Enumeration<String> keyAliases = keyStore.aliases(); keyAliases.hasMoreElements(); ) { 536 537 final String keyAlias = keyAliases.nextElement(); 538 final char[] keyPassword = pwLookup == null ? "".toCharArray() : pwLookup.lookupPassword(keyAlias); 539 540 Certificate cert = keyStore.getCertificate(keyAlias); 541 if (cert == null) { 542 continue; // skip 543 } 544 545 if (cert.getPublicKey() instanceof RSAPublicKey) { 546 547 RSAKey rsaJWK; 548 try { 549 rsaJWK = RSAKey.load(keyStore, keyAlias, keyPassword); 550 } catch (JOSEException e) { 551 continue; // skip cert 552 } 553 554 if (rsaJWK == null) { 555 continue; // skip key 556 } 557 558 jwks.add(rsaJWK); 559 560 } else if (cert.getPublicKey() instanceof ECPublicKey) { 561 562 ECKey ecJWK; 563 try { 564 ecJWK = ECKey.load(keyStore, keyAlias, keyPassword); 565 } catch (JOSEException e) { 566 continue; // skip cert 567 } 568 569 if (ecJWK != null) { 570 jwks.add(ecJWK); 571 } 572 } 573 } 574 575 576 // Load symmetric keys 577 for (Enumeration<String> keyAliases = keyStore.aliases(); keyAliases.hasMoreElements(); ) { 578 579 final String keyAlias = keyAliases.nextElement(); 580 final char[] keyPassword = pwLookup == null ? "".toCharArray() : pwLookup.lookupPassword(keyAlias); 581 582 OctetSequenceKey octJWK; 583 try { 584 octJWK = OctetSequenceKey.load(keyStore, keyAlias, keyPassword); 585 } catch (JOSEException e) { 586 continue; // skip key 587 } 588 589 if (octJWK != null) { 590 jwks.add(octJWK); 591 } 592 } 593 594 return new JWKSet(jwks); 595 } 596}