Source for gnu.java.security.Engine

   1: /* Engine -- generic getInstance method.
   2:    Copyright (C) 2003, 2006  Free Software Foundation, Inc.
   3: 
   4: This file is part of GNU Classpath.
   5: 
   6: GNU Classpath is free software; you can redistribute it and/or modify
   7: it under the terms of the GNU General Public License as published by
   8: the Free Software Foundation; either version 2, or (at your option)
   9: any later version.
  10: 
  11: GNU Classpath is distributed in the hope that it will be useful, but
  12: WITHOUT ANY WARRANTY; without even the implied warranty of
  13: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  14: General Public License for more details.
  15: 
  16: You should have received a copy of the GNU General Public License
  17: along with GNU Classpath; see the file COPYING.  If not, write to the
  18: Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  19: 02110-1301 USA.
  20: 
  21: Linking this library statically or dynamically with other modules is
  22: making a combined work based on this library.  Thus, the terms and
  23: conditions of the GNU General Public License cover the whole
  24: combination.
  25: 
  26: As a special exception, the copyright holders of this library give you
  27: permission to link this library with independent modules to produce an
  28: executable, regardless of the license terms of these independent
  29: modules, and to copy and distribute the resulting executable under
  30: terms of your choice, provided that you also meet, for each linked
  31: independent module, the terms and conditions of the license of that
  32: module.  An independent module is a module which is not derived from
  33: or based on this library.  If you modify this library, you may extend
  34: this exception to your version of the library, but you are not
  35: obligated to do so.  If you do not wish to do so, delete this
  36: exception statement from your version. */
  37: 
  38: package gnu.java.security;
  39: 
  40: import java.lang.reflect.Constructor;
  41: import java.lang.reflect.InvocationTargetException;
  42: 
  43: import java.security.NoSuchAlgorithmException;
  44: import java.security.Provider;
  45: import java.util.Enumeration;
  46: 
  47: /**
  48:  * Generic implementation of the getInstance methods in the various
  49:  * engine classes in java.security.
  50:  * <p>
  51:  * These classes ({@link java.security.Signature} for example) can be
  52:  * thought of as the "chrome, upholstery, and steering wheel", and the SPI
  53:  * (service provider interface, e.g. {@link java.security.SignatureSpi})
  54:  * classes can be thought of as the "engine" -- providing the actual
  55:  * functionality of whatever cryptographic algorithm the instance
  56:  * represents.
  57:  *
  58:  * @see Provider
  59:  * @author Casey Marshall 
  60:  */
  61: public final class Engine
  62: {
  63: 
  64:   // Constants.
  65:   // ------------------------------------------------------------------------
  66: 
  67:   /** Prefix for aliases. */
  68:   private static final String ALG_ALIAS = "Alg.Alias.";
  69: 
  70:   /** Maximum number of aliases to try. */
  71:   private static final int MAX_ALIASES = 5;
  72: 
  73:   /** Argument list for no-argument constructors. */
  74:   private static final Object[] NO_ARGS = new Object[0];
  75: 
  76:   // Constructor.
  77:   // ------------------------------------------------------------------------
  78: 
  79:   /** This class cannot be instantiated. */
  80:   private Engine() { }
  81: 
  82:   // Class method.
  83:   // ------------------------------------------------------------------------
  84: 
  85:   /**
  86:    * Get the implementation for <i>algorithm</i> for service
  87:    * <i>service</i> from <i>provider</i>. The service is e.g.
  88:    * "Signature", and the algorithm "DSA".
  89:    *
  90:    * @param service   The service name.
  91:    * @param algorithm The name of the algorithm to get.
  92:    * @param provider  The provider to get the implementation from.
  93:    * @return The engine class for the specified algorithm; the object
  94:    *         returned is typically a subclass of the SPI class for that
  95:    *         service, but callers should check that this is so.
  96:    * @throws NoSuchAlgorithmException If the implementation cannot be
  97:    *         found or cannot be instantiated.
  98:    * @throws InvocationTargetException If the SPI class's constructor
  99:    *         throws an exception.
 100:    * @throws IllegalArgumentException If any of the three arguments are null.
 101:    */
 102:   public static Object getInstance(String service, String algorithm,
 103:                                    Provider provider)
 104:     throws InvocationTargetException, NoSuchAlgorithmException
 105:   {
 106:     return getInstance(service, algorithm, provider, NO_ARGS);
 107:   }
 108: 
 109:   /**
 110:    * Get the implementation for <i>algorithm</i> for service
 111:    * <i>service</i> from <i>provider</i>, passing <i>initArgs</i> to the
 112:    * SPI class's constructor (which cannot be null; pass a zero-length
 113:    * array if the SPI takes no arguments). The service is e.g.
 114:    * "Signature", and the algorithm "DSA".
 115:    *
 116:    * @param service   The service name.
 117:    * @param algorithm The name of the algorithm to get.
 118:    * @param provider  The provider to get the implementation from.
 119:    * @param initArgs  The arguments to pass to the SPI class's
 120:    *        constructor (cannot be null).
 121:    * @return The engine class for the specified algorithm; the object
 122:    *         returned is typically a subclass of the SPI class for that
 123:    *         service, but callers should check that this is so.
 124:    * @throws NoSuchAlgorithmException If the implementation cannot be
 125:    *         found or cannot be instantiated.
 126:    * @throws InvocationTargetException If the SPI class's constructor
 127:    *         throws an exception.
 128:    * @throws IllegalArgumentException If any of the four arguments are null.
 129:    */
 130:   public static Object getInstance(String service, String algorithm,
 131:                                    Provider provider, Object[] initArgs)
 132:     throws InvocationTargetException, NoSuchAlgorithmException
 133:   {
 134:     if (service != null)
 135:       service = service.trim();
 136: 
 137:     if (algorithm != null)
 138:       algorithm = algorithm.trim();
 139: 
 140:     if (service == null || service.length() == 0
 141:         || algorithm == null || algorithm.length() == 0
 142:         || provider == null || initArgs == null)
 143:       throw new IllegalArgumentException();
 144: 
 145:     
 146:     Enumeration enumer = provider.propertyNames();
 147:     String key;
 148:     String alias;
 149:     int count = 0;
 150:     boolean algorithmFound = false;
 151: 
 152:     while (enumer.hasMoreElements())
 153:       {
 154:         key = (String) enumer.nextElement();
 155: 
 156:         if (key.equalsIgnoreCase(service + "." + algorithm))
 157:           {
 158:             // remove the service portion from the key
 159:             algorithm = key.substring(service.length() + 1); 
 160:             
 161:             algorithmFound = true;
 162:             break;
 163: 
 164:           }
 165:         else if (key.equalsIgnoreCase(ALG_ALIAS + service + "." + algorithm))
 166:           {
 167: 
 168:             alias = (String) provider.getProperty(key);
 169:             
 170:             if (! algorithm.equalsIgnoreCase(alias)) // does not refer to itself
 171:               {
 172:                 algorithm = alias;
 173:                 if (count++ > MAX_ALIASES)
 174:                   throw new NoSuchAlgorithmException("too many aliases");
 175:                 
 176:                 // need to reset enumeration to now look for the alias
 177:                 enumer = provider.propertyNames();
 178:               }
 179:           }
 180:       }
 181:     
 182:     if (! algorithmFound)
 183:       {
 184:         throw new NoSuchAlgorithmException(algorithm);
 185:       }
 186:     
 187:     
 188:     // Find and instantiate the implementation.
 189:     Class clazz = null;
 190:     ClassLoader loader = provider.getClass().getClassLoader();
 191:     Constructor constructor = null;
 192:     String error = algorithm;
 193: 
 194:     try
 195:       {
 196:         if (loader != null)
 197:           clazz = loader.loadClass(provider.getProperty(service+"."+algorithm));
 198:         else
 199:           clazz = Class.forName(provider.getProperty(service+"."+algorithm));
 200:         constructor = getCompatibleConstructor(clazz, initArgs);
 201:         return constructor.newInstance(initArgs);
 202:       }
 203:     catch (ClassNotFoundException cnfe)
 204:       {
 205:         error = "class not found: " + algorithm;
 206:       }
 207:     catch (IllegalAccessException iae)
 208:       {
 209:         error = "illegal access: " + iae.getMessage();
 210:       }
 211:     catch (InstantiationException ie)
 212:       {
 213:         error = "instantiation exception: " + ie.getMessage();
 214:       }
 215:     catch (ExceptionInInitializerError eiie)
 216:       {
 217:         error = "exception in initializer: " + eiie.getMessage();
 218:       }
 219:     catch (SecurityException se)
 220:       {
 221:         error = "security exception: " + se.getMessage();
 222:       }
 223:     catch (NoSuchMethodException nsme)
 224:       {
 225:         error = "no appropriate constructor found";
 226:       }
 227: 
 228:     throw new NoSuchAlgorithmException(error);
 229:   }
 230: 
 231:   // Own methods.
 232:   // ------------------------------------------------------------------------
 233: 
 234:   /**
 235:    * Find a constructor in the given class that can take the specified
 236:    * argument list, allowing any of which to be null.
 237:    *
 238:    * @param clazz    The class from which to get the constructor.
 239:    * @param initArgs The argument list to be passed to the constructor.
 240:    * @return The constructor.
 241:    * @throws NoSuchMethodException If no constructor of the given class
 242:    *         can take the specified argument array.
 243:    */
 244:   private static Constructor getCompatibleConstructor(Class clazz,
 245:                                                       Object[] initArgs)
 246:     throws NoSuchMethodException
 247:   {
 248:     Constructor[] c = clazz.getConstructors();
 249:     outer:for (int i = 0; i < c.length; i++)
 250:       {
 251:         Class[] argTypes = c[i].getParameterTypes();
 252:         if (argTypes.length != initArgs.length)
 253:           continue;
 254:         for (int j = 0; j < argTypes.length; j++)
 255:           {
 256:             if (initArgs[j] != null &&
 257:                 !argTypes[j].isAssignableFrom(initArgs[j].getClass()))
 258:               continue outer;
 259:           }
 260:         // If we reach this point, we know this constructor (c[i]) has
 261:         // the same number of parameters as the target parameter list,
 262:         // and all our parameters are either (1) null, or (2) assignable
 263:         // to the target parameter type.
 264:         return c[i];
 265:       }
 266:     throw new NoSuchMethodException();
 267:   }
 268: }