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:   /**
  83:    * Return the implementation for <i>algorithm</i> for service <i>service</i>
  84:    * from <i>provider</i>. The service is e.g. "Signature", and the algorithm
  85:    * "DSA".
  86:    * 
  87:    * @param service The service name.
  88:    * @param algorithm The name of the algorithm to get.
  89:    * @param provider The provider to get the implementation from.
  90:    * @return The engine class for the specified algorithm; the object returned
  91:    *         is typically a subclass of the SPI class for that service, but
  92:    *         callers should check that this is so.
  93:    * @throws NoSuchAlgorithmException If the implementation cannot be found or
  94:    *           cannot be instantiated.
  95:    * @throws InvocationTargetException If the SPI class's constructor throws an
  96:    *           exception.
  97:    * @throws IllegalArgumentException If any of the three arguments is null.
  98:    */
  99:   public static Object getInstance(String service, String algorithm,
 100:                                    Provider provider)
 101:       throws InvocationTargetException, NoSuchAlgorithmException
 102:   {
 103:     return getInstance(service, algorithm, provider, NO_ARGS);
 104:   }
 105: 
 106:   /**
 107:    * Return the implementation for <i>algorithm</i> for service <i>service</i>
 108:    * from <i>provider</i>, passing <i>initArgs</i> to the SPI class's
 109:    * constructor (which cannot be null; pass a zero-length array if the SPI
 110:    * takes no arguments). The service is e.g. "Signature", and the algorithm
 111:    * "DSA".
 112:    * 
 113:    * @param service The service name.
 114:    * @param algorithm The name of the algorithm to get.
 115:    * @param provider The provider to get the implementation from.
 116:    * @param initArgs The arguments to pass to the SPI class's constructor
 117:    *          (cannot be null).
 118:    * @return The engine class for the specified algorithm; the object returned
 119:    *         is typically a subclass of the SPI class for that service, but
 120:    *         callers should check that this is so.
 121:    * @throws NoSuchAlgorithmException If the implementation cannot be found or
 122:    *           cannot be instantiated.
 123:    * @throws InvocationTargetException If the SPI class's constructor throws an
 124:    *           exception.
 125:    * @throws IllegalArgumentException If any of the four arguments is
 126:    *           <code>null</code> or if either <code>service</code>, or
 127:    *           <code>algorithm</code> is an empty string.
 128:    */
 129:   public static Object getInstance(String service, String algorithm,
 130:                                    Provider provider, Object[] initArgs)
 131:       throws InvocationTargetException, NoSuchAlgorithmException
 132:   {
 133:     if (service == null)
 134:       throw new IllegalArgumentException("service MUST NOT be null");
 135:     service = service.trim();
 136:     if (service.length() == 0)
 137:       throw new IllegalArgumentException("service MUST NOT be empty");
 138:     if (algorithm == null)
 139:       throw new IllegalArgumentException("algorithm MUST NOT be null");
 140:     algorithm = algorithm.trim();
 141:     if (algorithm.length() == 0)
 142:       throw new IllegalArgumentException("algorithm MUST NOT be empty");
 143:     if (provider == null)
 144:       throw new IllegalArgumentException("provider MUST NOT be null");
 145:     if (initArgs == null)
 146:       throw new IllegalArgumentException("Constructor's parameters MUST NOT be null");
 147: 
 148:     Enumeration enumer = provider.propertyNames();
 149:     String key = null;
 150:     String alias;
 151:     int count = 0;
 152:     boolean algorithmFound = false;
 153:     StringBuilder sb = new StringBuilder();
 154:     while (enumer.hasMoreElements())
 155:       {
 156:         key = (String) enumer.nextElement();
 157:         if (key.equalsIgnoreCase(service + "." + algorithm))
 158:           {
 159:             // remove the service portion from the key
 160:             algorithm = key.substring(service.length() + 1); 
 161:             algorithmFound = true;
 162:             break;
 163:           }
 164:         else if (key.equalsIgnoreCase(ALG_ALIAS + service + "." + algorithm))
 165:           {
 166:             alias = (String) provider.getProperty(key);
 167:             if (! algorithm.equalsIgnoreCase(alias)) // does not refer to itself
 168:               {
 169:                 algorithm = alias;
 170:                 if (count++ > MAX_ALIASES)
 171:                   {
 172:                     sb.append("Algorithm [").append(algorithm)
 173:                         .append("] of type [").append(service)
 174:                         .append("] from provider [").append(provider)
 175:                         .append("] has too many aliases");
 176:                     throw new NoSuchAlgorithmException(sb.toString());
 177:                   }
 178:                 // need to reset enumeration to now look for the alias
 179:                 enumer = provider.propertyNames();
 180:               }
 181:           }
 182:       }
 183: 
 184:     if (! algorithmFound)
 185:       {
 186:         sb.append("Algorithm [").append(algorithm).append("] of type [")
 187:             .append(service).append("] from provider [")
 188:             .append(provider).append("] is not found");
 189:         throw new NoSuchAlgorithmException(sb.toString());
 190:       }
 191: 
 192:     // Find and instantiate the implementation
 193:     Class clazz = null;
 194:     ClassLoader loader = provider.getClass().getClassLoader();
 195:     Constructor constructor = null;
 196:     String className = provider.getProperty(key);
 197:     sb.append("Class [").append(className).append("] for algorithm [")
 198:         .append(algorithm).append("] of type [").append(service)
 199:         .append("] from provider [").append(provider).append("] ");
 200:     Throwable cause = null;
 201:     try
 202:       {
 203:         if (loader != null)
 204:           clazz = loader.loadClass(className);
 205:         else
 206:           clazz = Class.forName(className);
 207:         constructor = getCompatibleConstructor(clazz, initArgs);
 208:         return constructor.newInstance(initArgs);
 209:       }
 210:     catch (ClassNotFoundException x)
 211:       {
 212:         sb.append("cannot not be found");
 213:         cause = x;
 214:       }
 215:     catch (IllegalAccessException x)
 216:       {
 217:         sb.append("cannot be accessed");
 218:         cause = x;
 219:       }
 220:     catch (InstantiationException x)
 221:       {
 222:         sb.append("cannot be instantiated");
 223:         cause = x;
 224:       }
 225:     catch (ExceptionInInitializerError x)
 226:       {
 227:         sb.append("cannot be initialized");
 228:         cause = x;
 229:       }
 230:     catch (SecurityException x)
 231:       {
 232:         sb.append("caused a security violation");
 233:         cause = x;
 234:       }
 235:     catch (NoSuchMethodException x)
 236:       {
 237:         sb.append("does not have/expose an appropriate constructor");
 238:         cause = x;
 239:       }
 240: 
 241:     NoSuchAlgorithmException x = new NoSuchAlgorithmException(sb.toString());
 242:     x.initCause(cause);
 243:     throw x;
 244:   }
 245: 
 246:   /**
 247:    * Find a constructor in the given class that can take the specified
 248:    * argument list, allowing any of which to be null.
 249:    *
 250:    * @param clazz    The class from which to get the constructor.
 251:    * @param initArgs The argument list to be passed to the constructor.
 252:    * @return The constructor.
 253:    * @throws NoSuchMethodException If no constructor of the given class
 254:    *         can take the specified argument array.
 255:    */
 256:   private static Constructor getCompatibleConstructor(Class clazz,
 257:                                                       Object[] initArgs)
 258:     throws NoSuchMethodException
 259:   {
 260:     Constructor[] c = clazz.getConstructors();
 261:     outer:for (int i = 0; i < c.length; i++)
 262:       {
 263:         Class[] argTypes = c[i].getParameterTypes();
 264:         if (argTypes.length != initArgs.length)
 265:           continue;
 266:         for (int j = 0; j < argTypes.length; j++)
 267:           {
 268:             if (initArgs[j] != null &&
 269:                 !argTypes[j].isAssignableFrom(initArgs[j].getClass()))
 270:               continue outer;
 271:           }
 272:         // If we reach this point, we know this constructor (c[i]) has
 273:         // the same number of parameters as the target parameter list,
 274:         // and all our parameters are either (1) null, or (2) assignable
 275:         // to the target parameter type.
 276:         return c[i];
 277:       }
 278:     throw new NoSuchMethodException();
 279:   }
 280: }