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