001/* 002 * nimbus-jose-jwt 003 * 004 * Copyright 2012-2016, Connect2id Ltd. 005 * 006 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use 007 * this file except in compliance with the License. You may obtain a copy of the 008 * License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, software distributed 013 * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 014 * CONDITIONS OF ANY KIND, either express or implied. See the License for the 015 * specific language governing permissions and limitations under the License. 016 */ 017 018package com.nimbusds.jose.jwk; 019 020 021import java.security.Key; 022import java.security.KeyPair; 023import java.util.Collections; 024import java.util.LinkedList; 025import java.util.List; 026 027import com.nimbusds.jose.JOSEException; 028 029 030/** 031 * Key converter. 032 */ 033public class KeyConverter { 034 035 036 /** 037 * Converts the specified list of JSON Web Keys (JWK) their standard 038 * Java class representation. Asymmetric {@link RSAKey RSA} and 039 * {@link ECKey EC key} pairs are converted to 040 * {@link java.security.PublicKey} and {@link java.security.PrivateKey} 041 * (if specified) objects. {@link OctetSequenceKey secret JWKs} are 042 * converted to {@link javax.crypto.SecretKey} objects. Key conversion 043 * exceptions are silently ignored. 044 * 045 * @param jwkList The JWK list. May be {@code null}. 046 * 047 * @return The converted keys, empty set if none or {@code null}. 048 */ 049 public static List<Key> toJavaKeys(final List<JWK> jwkList) { 050 051 if (jwkList == null) { 052 return Collections.emptyList(); 053 } 054 055 List<Key> out = new LinkedList<>(); 056 for (JWK jwk: jwkList) { 057 try { 058 if (jwk instanceof AsymmetricJWK) { 059 KeyPair keyPair = ((AsymmetricJWK)jwk).toKeyPair(); 060 out.add(keyPair.getPublic()); // add public 061 if (keyPair.getPrivate() != null) { 062 out.add(keyPair.getPrivate()); // add private if present 063 } 064 } else if (jwk instanceof SecretJWK) { 065 out.add(((SecretJWK)jwk).toSecretKey()); 066 } 067 } catch (JOSEException e) { 068 // ignore and continue 069 } 070 } 071 return out; 072 } 073}