001package com.nimbusds.jose.jwk;
002
003
004import java.security.Key;
005import java.security.KeyPair;
006import java.util.Collections;
007import java.util.LinkedList;
008import java.util.List;
009
010import com.nimbusds.jose.JOSEException;
011
012
013/**
014 * Key converter.
015 */
016public class KeyConverter {
017        
018
019        /**
020         * Converts the specified list of JSON Web Keys (JWK) their standard
021         * Java class representation. Asymmetric {@link RSAKey RSA} and
022         * {@link ECKey EC key} pairs are converted to
023         * {@link java.security.PublicKey} and {@link java.security.PrivateKey}
024         * (if specified) objects. {@link OctetSequenceKey secret JWKs} are
025         * converted to {@link javax.crypto.SecretKey} objects. Key conversion
026         * exceptions are silently ignored.
027         *
028         * @param jwkList The JWK list. May be {@code null}.
029         *
030         * @return The converted keys, empty set if none or {@code null}.
031         */
032        public static List<Key> toJavaKeys(final List<JWK> jwkList) {
033
034                if (jwkList == null) {
035                        return Collections.emptyList();
036                }
037
038                List<Key> out = new LinkedList<>();
039                for (JWK jwk: jwkList) {
040                        try {
041                                if (jwk instanceof AssymetricJWK) {
042                                        KeyPair keyPair = ((AssymetricJWK)jwk).toKeyPair();
043                                        out.add(keyPair.getPublic()); // add public
044                                        if (keyPair.getPrivate() != null) {
045                                                out.add(keyPair.getPrivate()); // add private if present
046                                        }
047                                } else if (jwk instanceof SecretJWK) {
048                                        out.add(((SecretJWK)jwk).toSecretKey());
049                                }
050                        } catch (JOSEException e) {
051                                // ignore and continue
052                        }
053                }
054                return out;
055        }
056}