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 ForgeRock AS.
015*/
016package org.forgerock.jaspi.modules.openid.helpers;
017
018import java.security.Key;
019import javax.crypto.spec.SecretKeySpec;
020import org.forgerock.jaspi.modules.openid.exceptions.FailedToLoadJWKException;
021import org.forgerock.json.JsonException;
022import org.forgerock.json.jose.jwk.EcJWK;
023import org.forgerock.json.jose.jwk.KeyType;
024import org.forgerock.json.jose.jwk.OctJWK;
025import org.forgerock.json.jose.jwk.RsaJWK;
026import org.forgerock.json.jose.jws.JwsAlgorithm;
027
028/**
029 * Helper class to look up and return the keys from specific JWK implementation
030 * algorithm types.
031 */
032public class JWKLookup {
033
034    /**
035     * Lookup returns the key from the given json, under the assumption it's of the correct
036     * keyType.
037     *
038     * @param json JSON from which to attempt to generate a key
039     * @param keyType The type of key we expect to be generated from the JSON
040     * @return a valid key for verifying a JWT
041     * @throws FailedToLoadJWKException If there's an issue handling the loading of the JWK
042     */
043    public Key lookup(String json, KeyType keyType) throws FailedToLoadJWKException {
044        try {
045            switch (keyType) {
046            case RSA:
047                final RsaJWK rsaJWK = RsaJWK.parse(json);
048                return rsaJWK.toRSAPublicKey();
049            case EC:
050                final EcJWK ecJWK = EcJWK.parse(json);
051                return ecJWK.toECPublicKey();
052            case OCT:
053                final OctJWK octJWK = OctJWK.parse(json);
054                final String jwkKey = octJWK.getKey();
055
056                final Key key = new SecretKeySpec(jwkKey.getBytes(),
057                        JwsAlgorithm.getJwsAlgorithm(octJWK.getAlgorithm()).getMdAlgorithm());
058
059                return key;
060            default:
061                throw new FailedToLoadJWKException("Unable to find handler for Key Type");
062            }
063        } catch (JsonException je) {
064            throw new FailedToLoadJWKException("Unable to generate Key from provided JSON", je);
065        }
066    }
067
068}