001    /* KeyFactory.java --- Key Factory Class
002       Copyright (C) 1999, 2003, 2004  Free Software Foundation, Inc.
003    
004    This file is part of GNU Classpath.
005    
006    GNU Classpath is free software; you can redistribute it and/or modify
007    it under the terms of the GNU General Public License as published by
008    the Free Software Foundation; either version 2, or (at your option)
009    any later version.
010    
011    GNU Classpath is distributed in the hope that it will be useful, but
012    WITHOUT ANY WARRANTY; without even the implied warranty of
013    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
014    General Public License for more details.
015    
016    You should have received a copy of the GNU General Public License
017    along with GNU Classpath; see the file COPYING.  If not, write to the
018    Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
019    02110-1301 USA.
020    
021    Linking this library statically or dynamically with other modules is
022    making a combined work based on this library.  Thus, the terms and
023    conditions of the GNU General Public License cover the whole
024    combination.
025    
026    As a special exception, the copyright holders of this library give you
027    permission to link this library with independent modules to produce an
028    executable, regardless of the license terms of these independent
029    modules, and to copy and distribute the resulting executable under
030    terms of your choice, provided that you also meet, for each linked
031    independent module, the terms and conditions of the license of that
032    module.  An independent module is a module which is not derived from
033    or based on this library.  If you modify this library, you may extend
034    this exception to your version of the library, but you are not
035    obligated to do so.  If you do not wish to do so, delete this
036    exception statement from your version. */
037    
038    
039    package java.security;
040    
041    import gnu.java.security.Engine;
042    
043    import java.lang.reflect.InvocationTargetException;
044    import java.security.spec.InvalidKeySpecException;
045    import java.security.spec.KeySpec;
046    
047    /**
048     * Key factories are used to convert keys (opaque cryptographic keys of type
049     * {@link Key}) into key specifications (transparent representations of the
050     * underlying key material).
051     * 
052     * <p>Key factories are bi-directional. They allow a key class to be converted
053     * into a key specification (key material) and back again. For example DSA
054     * public keys can be specified as <code>DSAPublicKeySpec</code> or
055     * <code>X509EncodedKeySpec</code>. A key factory translates these key
056     * specifications.</p>
057     *
058     * @since 1.2
059     * @see Key
060     * @see KeySpec
061     * @see java.security.spec.DSAPublicKeySpec
062     * @see java.security.spec.X509EncodedKeySpec
063       @author Mark Benvenuto
064     */
065    public class KeyFactory
066    {
067      /** The service name for key factories. */
068      private static final String KEY_FACTORY = "KeyFactory";
069    
070      private KeyFactorySpi keyFacSpi;
071      private Provider provider;
072      private String algorithm;
073    
074      /**
075       * Constructs a new instance of <code>KeyFactory</code> with the specified
076       * parameters.
077       * 
078       * @param keyFacSpi
079       *          the key factory to use.
080       * @param provider
081       *          the provider to use.
082       * @param algorithm
083       *          the name of the key algorithm to use.
084       */
085      protected KeyFactory(KeyFactorySpi keyFacSpi, Provider provider,
086                           String algorithm)
087      {
088        this.keyFacSpi = keyFacSpi;
089        this.provider = provider;
090        this.algorithm = algorithm;
091      }
092    
093      /**
094       * Returns a new instance of <code>KeyFactory</code> representing the
095       * specified key factory.
096       * 
097       * @param algorithm the name of algorithm to use.
098       * @return a new instance repesenting the desired algorithm.
099       * @throws NoSuchAlgorithmException if the algorithm is not implemented by any
100       *           provider.
101       * @throws IllegalArgumentException if <code>algorithm</code> is
102       *           <code>null</code> or is an empty string.
103       */
104      public static KeyFactory getInstance(String algorithm)
105          throws NoSuchAlgorithmException
106      {
107        Provider[] p = Security.getProviders();
108        NoSuchAlgorithmException lastException = null;
109        for (int i = 0; i < p.length; i++)
110          try
111            {
112              return getInstance(algorithm, p[i]);
113            }
114          catch (NoSuchAlgorithmException x)
115            {
116              lastException = x;
117            }
118        if (lastException != null)
119          throw lastException;
120        throw new NoSuchAlgorithmException(algorithm);
121      }
122    
123      /**
124       * Returns a new instance of <code>KeyFactory</code> representing the
125       * specified key factory from the specified provider.
126       * 
127       * @param algorithm the name of algorithm to use.
128       * @param provider the name of the provider to use.
129       * @return a new instance repesenting the desired algorithm.
130       * @throws NoSuchAlgorithmException if the algorithm is not implemented by the
131       *           named provider.
132       * @throws NoSuchProviderException if the named provider was not found.
133       * @throws IllegalArgumentException if either <code>algorithm</code> or
134       *           <code>provider</code> is <code>null</code> or empty.
135       */
136      public static KeyFactory getInstance(String algorithm, String provider)
137          throws NoSuchAlgorithmException, NoSuchProviderException
138      {
139        if (provider == null)
140          throw new IllegalArgumentException("provider MUST NOT be null");
141        provider = provider.trim();
142        if (provider.length() == 0)
143          throw new IllegalArgumentException("provider MUST NOT be empty");
144        Provider p = Security.getProvider(provider);
145        if (p == null)
146          throw new NoSuchProviderException(provider);
147        return getInstance(algorithm, p);
148      }
149    
150      /**
151       * Returns a new instance of <code>KeyFactory</code> representing the
152       * specified key factory from the designated {@link Provider}.
153       * 
154       * @param algorithm the name of algorithm to use.
155       * @param provider the {@link Provider} to use.
156       * @return a new instance repesenting the desired algorithm.
157       * @throws NoSuchAlgorithmException if the algorithm is not implemented by
158       *           {@link Provider}.
159       * @throws IllegalArgumentException if either <code>algorithm</code> or
160       *           <code>provider</code> is <code>null</code>, or if
161       *           <code>algorithm</code> is an empty string.
162       * @since 1.4
163       * @see Provider
164       */
165      public static KeyFactory getInstance(String algorithm, Provider provider)
166          throws NoSuchAlgorithmException
167      {
168        StringBuilder sb = new StringBuilder("KeyFactory for algorithm [")
169            .append(algorithm).append("] from provider[")
170            .append(provider).append("] could not be created");
171        Throwable cause;
172        try
173          {
174            Object spi = Engine.getInstance(KEY_FACTORY, algorithm, provider);
175            return new KeyFactory((KeyFactorySpi) spi, provider, algorithm);
176          }
177        catch (InvocationTargetException x)
178          {
179            cause = x.getCause();
180            if (cause instanceof NoSuchAlgorithmException)
181              throw (NoSuchAlgorithmException) cause;
182            if (cause == null)
183              cause = x;
184          }
185        catch (ClassCastException x)
186          {
187            cause = x;
188          }
189        NoSuchAlgorithmException x = new NoSuchAlgorithmException(sb.toString());
190        x.initCause(cause);
191        throw x;
192      }
193    
194      /**
195       * Returns the {@link Provider} of this instance.
196       * 
197       * @return the {@link Provider} of this instance.
198       */
199      public final Provider getProvider()
200      {
201        return provider;
202      }
203    
204      /**
205       * Returns the name of the algorithm used.
206       * 
207       * @return the name of the algorithm used.
208       */
209      public final String getAlgorithm()
210      {
211        return algorithm;
212      }
213    
214      /**
215       * Generates a public key from the provided key specification.
216       * 
217       * @param keySpec
218       *          the key specification.
219       * @return the public key.
220       * @throws InvalidKeySpecException
221       *           if the key specification is invalid.
222       */
223      public final PublicKey generatePublic(KeySpec keySpec)
224        throws InvalidKeySpecException
225      {
226        return keyFacSpi.engineGeneratePublic(keySpec);
227      }
228    
229      /**
230       * Generates a private key from the provided key specification.
231       * 
232       * @param keySpec
233       *          the key specification.
234       * @return the private key.
235       * @throws InvalidKeySpecException
236       *           if the key specification is invalid.
237       */
238      public final PrivateKey generatePrivate(KeySpec keySpec)
239        throws InvalidKeySpecException
240      {
241        return keyFacSpi.engineGeneratePrivate(keySpec);
242      }
243    
244      /**
245       * Returns a key specification for the given key. <code>keySpec</code>
246       * identifies the specification class to return the key material in.
247       * 
248       * @param key
249       *          the key to use.
250       * @param keySpec
251       *          the specification class to use.
252       * @return the key specification in an instance of the requested specification
253       *         class.
254       * @throws InvalidKeySpecException
255       *           the requested key specification is inappropriate for this key or
256       *           the key is unrecognized.
257       */
258      public final <T extends KeySpec> T getKeySpec(Key key, Class<T> keySpec)
259        throws InvalidKeySpecException
260      {
261        return keyFacSpi.engineGetKeySpec(key, keySpec);
262      }
263    
264      /**
265       * Translates the key from an unknown or untrusted provider into a key from
266       * this key factory.
267       * 
268       * @param key
269       *          the key to translate from.
270       * @return the translated key.
271       * @throws InvalidKeyException
272       *           if the key cannot be processed by this key factory.
273       */
274      public final Key translateKey(Key key) throws InvalidKeyException
275      {
276        return keyFacSpi.engineTranslateKey(key);
277      }
278    }