1 /*
2 * The contents of this file are subject to the terms of the Common Development and
3 * Distribution License (the License). You may not use this file except in compliance with the
4 * License.
5 *
6 * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
7 * specific language governing permission and limitations under the License.
8 *
9 * When distributing Covered Software, include this CDDL Header Notice in each file and include
10 * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
11 * Header, with the fields enclosed by brackets [] replaced by your own identifying
12 * information: "Portions copyright [year] [name of copyright owner]".
13 *
14 * Copyright 2014-2017 ForgeRock AS.
15 */
16 package org.forgerock.json.jose.jwk;
17
18 import java.security.Key;
19 import javax.crypto.spec.SecretKeySpec;
20 import org.forgerock.json.JsonException;
21 import org.forgerock.json.jose.exceptions.FailedToLoadJWKException;
22 import org.forgerock.json.jose.jws.JwsAlgorithm;
23
24 /**
25 * Helper class to look up and return the keys from specific JWK implementation
26 * algorithm types.
27 */
28 public class JWKLookup {
29
30 /**
31 * Lookup returns the key from the given json, under the assumption it's of the correct
32 * keyType.
33 *
34 * @param json JSON from which to attempt to generate a key
35 * @param keyType The type of key we expect to be generated from the JSON
36 * @return a valid key for verifying a JWT
37 * @throws FailedToLoadJWKException If there's an issue handling the loading of the JWK
38 */
39 public Key lookup(String json, KeyType keyType) throws FailedToLoadJWKException {
40 try {
41 switch (keyType) {
42 case RSA:
43 final RsaJWK rsaJWK = RsaJWK.parse(json);
44 return rsaJWK.toRSAPublicKey();
45 case EC:
46 final EcJWK ecJWK = EcJWK.parse(json);
47 return ecJWK.toECPublicKey();
48 case OCT:
49 final OctJWK octJWK = OctJWK.parse(json);
50 final String jwkKey = octJWK.getKey();
51
52 final Key key = new SecretKeySpec(jwkKey.getBytes(),
53 JwsAlgorithm.parseCryptographicAlgorithm(octJWK.getAlgorithm()).getMdAlgorithm());
54
55 return key;
56 default:
57 throw new FailedToLoadJWKException("Unable to find handler for Key Type");
58 }
59 } catch (JsonException je) {
60 throw new FailedToLoadJWKException("Unable to generate Key from provided JSON", je);
61 }
62 }
63
64 }