001/* 002* The contents of this file are subject to the terms of the Common Development and 003* Distribution License (the License). You may not use this file except in compliance with the 004* License. 005* 006* You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the 007* specific language governing permission and limitations under the License. 008* 009* When distributing Covered Software, include this CDDL Header Notice in each file and include 010* the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL 011* Header, with the fields enclosed by brackets [] replaced by your own identifying 012* information: "Portions copyright [year] [name of copyright owner]". 013* 014* Copyright 2014-2017 ForgeRock AS. 015*/ 016package org.forgerock.json.jose.jwk; 017 018import java.security.Key; 019import javax.crypto.spec.SecretKeySpec; 020import org.forgerock.json.JsonException; 021import org.forgerock.json.jose.exceptions.FailedToLoadJWKException; 022import org.forgerock.json.jose.jws.JwsAlgorithm; 023 024/** 025 * Helper class to look up and return the keys from specific JWK implementation 026 * algorithm types. 027 */ 028public class JWKLookup { 029 030 /** 031 * Lookup returns the key from the given json, under the assumption it's of the correct 032 * keyType. 033 * 034 * @param json JSON from which to attempt to generate a key 035 * @param keyType The type of key we expect to be generated from the JSON 036 * @return a valid key for verifying a JWT 037 * @throws FailedToLoadJWKException If there's an issue handling the loading of the JWK 038 */ 039 public Key lookup(String json, KeyType keyType) throws FailedToLoadJWKException { 040 try { 041 switch (keyType) { 042 case RSA: 043 final RsaJWK rsaJWK = RsaJWK.parse(json); 044 return rsaJWK.toRSAPublicKey(); 045 case EC: 046 final EcJWK ecJWK = EcJWK.parse(json); 047 return ecJWK.toECPublicKey(); 048 case OCT: 049 final OctJWK octJWK = OctJWK.parse(json); 050 final String jwkKey = octJWK.getKey(); 051 052 final Key key = new SecretKeySpec(jwkKey.getBytes(), 053 JwsAlgorithm.parseCryptographicAlgorithm(octJWK.getAlgorithm()).getMdAlgorithm()); 054 055 return key; 056 default: 057 throw new FailedToLoadJWKException("Unable to find handler for Key Type"); 058 } 059 } catch (JsonException je) { 060 throw new FailedToLoadJWKException("Unable to generate Key from provided JSON", je); 061 } 062 } 063 064}