001/* SecretKeyFactory.java -- Factory for creating secret keys.
002   Copyright (C) 2004  Free Software Foundation, Inc.
003
004This file is part of GNU Classpath.
005
006GNU Classpath is free software; you can redistribute it and/or modify
007it under the terms of the GNU General Public License as published by
008the Free Software Foundation; either version 2, or (at your option)
009any later version.
010
011GNU Classpath is distributed in the hope that it will be useful, but
012WITHOUT ANY WARRANTY; without even the implied warranty of
013MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
014General Public License for more details.
015
016You should have received a copy of the GNU General Public License
017along with GNU Classpath; see the file COPYING.  If not, write to the
018Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
01902110-1301 USA.
020
021Linking this library statically or dynamically with other modules is
022making a combined work based on this library.  Thus, the terms and
023conditions of the GNU General Public License cover the whole
024combination.
025
026As a special exception, the copyright holders of this library give you
027permission to link this library with independent modules to produce an
028executable, regardless of the license terms of these independent
029modules, and to copy and distribute the resulting executable under
030terms of your choice, provided that you also meet, for each linked
031independent module, the terms and conditions of the license of that
032module.  An independent module is a module which is not derived from
033or based on this library.  If you modify this library, you may extend
034this exception to your version of the library, but you are not
035obligated to do so.  If you do not wish to do so, delete this
036exception statement from your version. */
037
038
039package javax.crypto;
040
041import gnu.java.security.Engine;
042
043import java.lang.reflect.InvocationTargetException;
044import java.security.InvalidKeyException;
045import java.security.NoSuchAlgorithmException;
046import java.security.NoSuchProviderException;
047import java.security.Provider;
048import java.security.Security;
049import java.security.spec.InvalidKeySpecException;
050import java.security.spec.KeySpec;
051
052/**
053 * A secret key factory translates {@link SecretKey} objects to and from
054 * {@link java.security.spec.KeySpec} objects, and can translate between
055 * different vendors' representations of {@link SecretKey} objects (for
056 * security or semantics; whichever applies).
057 *
058 * @author Casey Marshall (csm@gnu.org)
059 * @since 1.4
060 * @see SecretKey
061 */
062public class SecretKeyFactory
063{
064
065  // Constants and fields.
066  // ------------------------------------------------------------------------
067
068  private static final String SERVICE = "SecretKeyFactory";
069
070  /** The underlying factory implementation. */
071  private SecretKeyFactorySpi skfSpi;
072
073  /** The provider of the implementation. */
074  private Provider provider;
075
076  /** The name of the algorithm. */
077  private String algorithm;
078
079  // Constructor.
080  // ------------------------------------------------------------------------
081
082  /**
083   * Create a new secret key factory.
084   *
085   * @param skfSpi   The underlying factory implementation.
086   * @param provider The provider.
087   * @param algorithm The algorithm name.
088   */
089  protected SecretKeyFactory(SecretKeyFactorySpi skfSpi, Provider provider,
090                             String algorithm)
091  {
092    this.skfSpi = skfSpi;
093    this.provider = provider;
094    this.algorithm = algorithm;
095  }
096
097  /**
098   * Create a new secret key factory from the first appropriate instance.
099   * 
100   * @param algorithm The algorithm name.
101   * @return The appropriate key factory, if found.
102   * @throws NoSuchAlgorithmException If no provider implements the specified
103   *           algorithm.
104   * @throws IllegalArgumentException if <code>algorithm</code> is
105   *           <code>null</code> or is an empty string.
106   */
107  public static final SecretKeyFactory getInstance(String algorithm)
108      throws NoSuchAlgorithmException
109  {
110    Provider[] p = Security.getProviders();
111    NoSuchAlgorithmException lastException = null;
112    for (int i = 0; i < p.length; i++)
113      try
114        {
115          return getInstance(algorithm, p[i]);
116        }
117      catch (NoSuchAlgorithmException x)
118        {
119          lastException = x;
120        }
121      if (lastException != null)
122        throw lastException;
123      throw new NoSuchAlgorithmException(algorithm);
124  }
125
126  /**
127   * Create a new secret key factory from the named provider.
128   * 
129   * @param algorithm The algorithm name.
130   * @param provider The provider name.
131   * @return The appropriate key factory, if found.
132   * @throws NoSuchAlgorithmException If the named provider does not implement
133   *           the algorithm.
134   * @throws NoSuchProviderException If the named provider does not exist.
135   * @throws IllegalArgumentException if either <code>algorithm</code> or
136   *           <code>provider</code> is <code>null</code>, or if
137   *           <code>algorithm</code> is an empty string.
138   */
139  public static final SecretKeyFactory getInstance(String algorithm,
140                                                   String provider)
141      throws NoSuchAlgorithmException, NoSuchProviderException
142  {
143    if (provider == null)
144      throw new IllegalArgumentException("provider MUST NOT be null");
145    Provider p = Security.getProvider(provider);
146    if (p == null)
147      throw new NoSuchProviderException(provider);
148    return getInstance(algorithm, p);
149  }
150
151  /**
152   * Create a new secret key factory from the specified provider.
153   * 
154   * @param algorithm The algorithm name.
155   * @param provider The provider.
156   * @return The appropriate key factory, if found.
157   * @throws NoSuchAlgorithmException If the provider does not implement the
158   *           algorithm.
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   */
163  public static final SecretKeyFactory getInstance(String algorithm,
164                                                   Provider provider)
165      throws NoSuchAlgorithmException
166  {
167    StringBuilder sb = new StringBuilder("SecretKeyFactory algorithm [")
168        .append(algorithm).append("] from provider[")
169        .append(provider).append("] could not be created");
170    Throwable cause;
171    try
172      {
173        Object spi = Engine.getInstance(SERVICE, algorithm, provider);
174        return new SecretKeyFactory((SecretKeyFactorySpi) spi, provider, algorithm);
175      }
176    catch (InvocationTargetException x)
177      {
178        cause = x.getCause();
179        if (cause instanceof NoSuchAlgorithmException)
180          throw (NoSuchAlgorithmException) cause;
181        if (cause == null)
182          cause = x;
183      }
184    catch (ClassCastException x)
185      {
186        cause = x;
187      }
188    NoSuchAlgorithmException x = new NoSuchAlgorithmException(sb.toString());
189    x.initCause(cause);
190    throw x;
191  }
192
193  /**
194   * Generate a secret key from a key specification, if possible.
195   *
196   * @param keySpec The key specification.
197   * @return The secret key.
198   * @throws java.security.InvalidKeySpecException If the key specification
199   *         cannot be transformed into a secret key.
200   */
201  public final SecretKey generateSecret(KeySpec keySpec)
202    throws InvalidKeySpecException
203  {
204    return skfSpi.engineGenerateSecret(keySpec);
205  }
206
207  /**
208   * Get the algorithm name.
209   *
210   * @return The algorithm name.
211   */
212  public final String getAlgorithm()
213  {
214    return algorithm;
215  }
216
217  /**
218   * Get the key specification from a secret key.
219   *
220   * @param key     The secret key.
221   * @param keySpec The target key specification class.
222   * @return The key specification.
223   * @throws java.security.spec.InvalidKeySpecException If the secret key cannot
224   *         be transformed into the specified key specification.
225   */
226  public final KeySpec getKeySpec(SecretKey key, Class keySpec)
227    throws InvalidKeySpecException
228  {
229    return skfSpi.engineGetKeySpec(key, keySpec);
230  }
231
232  /**
233   * Get the provider of this implementation.
234   *
235   * @return The provider.
236   */
237  public final Provider getProvider()
238  {
239    return provider;
240  }
241
242  /**
243   * Translate a secret key into another form.
244   *
245   * @param key The key to translate.
246   * @return The translated key.
247   * @throws java.security.InvalidKeyException If the argument cannot be
248   *         translated.
249   */
250  public final SecretKey translateKey(SecretKey key)
251    throws InvalidKeyException
252  {
253    return skfSpi.engineTranslateKey(key);
254  }
255}