001: /*
002: * @(#)CertificateFactory.java 1.23 06/10/10
003: *
004: * Copyright 1990-2006 Sun Microsystems, Inc. All Rights Reserved.
005: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
006: *
007: * This program is free software; you can redistribute it and/or
008: * modify it under the terms of the GNU General Public License version
009: * 2 only, as published by the Free Software Foundation.
010: *
011: * This program 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 version 2 for more details (a copy is
015: * included at /legal/license.txt).
016: *
017: * You should have received a copy of the GNU General Public License
018: * version 2 along with this work; if not, write to the Free Software
019: * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
020: * 02110-1301 USA
021: *
022: * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
023: * Clara, CA 95054 or visit www.sun.com if you need additional
024: * information or have any questions.
025: *
026: */
027:
028: package java.security.cert;
029:
030: import java.io.InputStream;
031: import java.util.Collection;
032: import java.util.Iterator;
033: import java.util.List;
034: import java.security.Provider;
035: import java.security.AccessController;
036: import java.security.PrivilegedAction;
037: import java.security.NoSuchAlgorithmException;
038: import java.security.NoSuchProviderException;
039: import java.lang.reflect.Method;
040: import java.lang.reflect.InvocationTargetException;
041:
042: /**
043: * This class defines the functionality of a certificate factory, which is
044: * used to generate certificate, certification path (<code>CertPath</code>)
045: * and certificate revocation list (CRL) objects from their encodings.
046: *
047: * <p>For encodings consisting of multiple certificates, use
048: * <code>generateCertificates</code> when you want to
049: * parse a collection of possibly unrelated certificates.
050: *
051: * <p>A certificate factory for X.509 must return certificates that are an
052: * instance of <code>java.security.cert.X509Certificate</code>, and CRLs
053: * that are an instance of <code>java.security.cert.X509CRL</code>.
054: *
055: * <p>The following example reads a file with Base64 encoded certificates,
056: * which are each bounded at the beginning by -----BEGIN CERTIFICATE-----, and
057: * bounded at the end by -----END CERTIFICATE-----. We convert the
058: * <code>FileInputStream</code> (which does not support <code>mark</code>
059: * and <code>reset</code>) to a <code>BufferedInputStream</code> (which
060: * supports those methods), so that each call to
061: * <code>generateCertificate</code> consumes only one certificate, and the
062: * read position of the input stream is positioned to the next certificate in
063: * the file:<p>
064: *
065: * <pre>
066: * FileInputStream fis = new FileInputStream(filename);
067: * BufferedInputStream bis = new BufferedInputStream(fis);
068: *
069: * CertificateFactory cf = CertificateFactory.getInstance("X.509");
070: *
071: * while (bis.available() > 0) {
072: * Certificate cert = cf.generateCertificate(bis);
073: * System.out.println(cert.toString());
074: * }
075: * </pre>
076: *
077: * <p>The following example parses a PKCS#7-formatted certificate reply stored
078: * in a file and extracts all the certificates from it:<p>
079: *
080: * <pre>
081: * FileInputStream fis = new FileInputStream(filename);
082: * CertificateFactory cf = CertificateFactory.getInstance("X.509");
083: * Collection c = cf.generateCertificates(fis);
084: * Iterator i = c.iterator();
085: * while (i.hasNext()) {
086: * Certificate cert = (Certificate)i.next();
087: * System.out.println(cert);
088: * }
089: * </pre>
090: *
091: * @author Hemma Prafullchandra
092: * @author Jan Luehe
093: * @author Sean Mullan
094: *
095: * @version 1.15, 02/02/00
096: *
097: * @see Certificate
098: * @see X509Certificate
099: * @see CertPath
100: * @see CRL
101: * @see X509CRL
102: *
103: * @since 1.2
104: */
105:
106: public class CertificateFactory {
107: // for use with the reflection API
108: private static final Class cl = java.security.Security.class;
109: private static final Class[] GET_IMPL_PARAMS = { String.class,
110: String.class, String.class };
111: private static final Class[] GET_IMPL_PARAMS2 = { String.class,
112: String.class, Provider.class };
113: // Get the implMethod via the name of a provider. Note: the name could
114: // be null.
115: private static Method implMethod;
116: // Get the implMethod2 via a Provider object.
117: private static Method implMethod2;
118: private static Boolean implMethod2Set = new Boolean(false);
119:
120: static {
121: implMethod = (Method) AccessController
122: .doPrivileged(new PrivilegedAction() {
123: public Object run() {
124: Method m = null;
125: try {
126: m = cl.getDeclaredMethod("getImpl",
127: GET_IMPL_PARAMS);
128: if (m != null)
129: m.setAccessible(true);
130: } catch (NoSuchMethodException nsme) {
131: }
132: return m;
133: }
134: });
135: }
136:
137: // The certificate type
138: private String type;
139:
140: // The provider
141: private Provider provider;
142:
143: // The provider implementation
144: private CertificateFactorySpi certFacSpi;
145:
146: /**
147: * Creates a CertificateFactory object of the given type, and encapsulates
148: * the given provider implementation (SPI object) in it.
149: *
150: * @param certFacSpi the provider implementation.
151: * @param provider the provider.
152: * @param type the certificate type.
153: */
154: protected CertificateFactory(CertificateFactorySpi certFacSpi,
155: Provider provider, String type) {
156: this .certFacSpi = certFacSpi;
157: this .provider = provider;
158: this .type = type;
159: }
160:
161: /**
162: * Generates a certificate factory object that implements the
163: * specified certificate type. If the default provider package
164: * provides an implementation of the requested certificate type,
165: * an instance of certificate factory containing that
166: * implementation is returned.
167: * If the type is not available in the default
168: * package, other packages are searched.
169: *
170: * @param type the name of the requested certificate type.
171: * See Appendix A in the <a href=
172: * "../../../../guide/security/CryptoSpec.html#AppA">
173: * Java Cryptography Architecture API Specification & Reference </a>
174: * for information about standard certificate types.
175: *
176: * @return a certificate factory object for the specified type.
177: *
178: * @exception CertificateException if the requested certificate type is
179: * not available in the default provider package or any of the other
180: * provider packages that were searched.
181: */
182: public static final CertificateFactory getInstance(String type)
183: throws CertificateException {
184: try {
185: if (implMethod == null) {
186: throw new CertificateException(type + " not found");
187: }
188:
189: // The underlying method is static, so we set the object
190: // argument to null.
191: Object[] objs = (Object[]) implMethod.invoke(null,
192: new Object[] { type, "CertificateFactory", null });
193: return new CertificateFactory(
194: (CertificateFactorySpi) objs[0],
195: (Provider) objs[1], type);
196: } catch (IllegalAccessException iae) {
197: CertificateException ce = new CertificateException(type
198: + " not found");
199: ce.initCause(iae);
200: throw ce;
201: } catch (InvocationTargetException ite) {
202: CertificateException ce = new CertificateException(type
203: + " not found");
204: ce.initCause(ite);
205: throw ce;
206: }
207: }
208:
209: /**
210: * Generates a certificate factory object for the specified
211: * certificate type from the specified provider.
212: *
213: * @param type the certificate type
214: * @param provider the name of the provider.
215: *
216: * @return a certificate factory object for the specified type.
217: *
218: * @exception CertificateException if the certificate type is
219: * not available from the specified provider.
220: *
221: * @exception NoSuchProviderException if the provider has not been
222: * configured.
223: *
224: * @see Provider
225: */
226: public static final CertificateFactory getInstance(String type,
227: String provider) throws CertificateException,
228: NoSuchProviderException {
229: if (provider == null || provider.length() == 0)
230: throw new IllegalArgumentException("missing provider");
231: try {
232: if (implMethod == null) {
233: throw new CertificateException(type + " not found");
234: }
235:
236: // The underlying method is static, so we set the object
237: // argument to null.
238: Object[] objs = (Object[]) implMethod
239: .invoke(null, new Object[] { type,
240: "CertificateFactory", provider });
241: return new CertificateFactory(
242: (CertificateFactorySpi) objs[0],
243: (Provider) objs[1], type);
244: } catch (IllegalAccessException iae) {
245: CertificateException ce = new CertificateException(type
246: + " not found");
247: ce.initCause(iae);
248: throw ce;
249: } catch (InvocationTargetException ite) {
250: Throwable t = ite.getTargetException();
251: if (t != null && t instanceof NoSuchProviderException)
252: throw (NoSuchProviderException) t;
253: CertificateException ce = new CertificateException(type
254: + " not found");
255: ce.initCause(ite);
256: throw ce;
257: }
258: }
259:
260: /**
261: * Generates a certificate factory object for the specified
262: * certificate type from the specified provider.
263: * Note: the <code>provider</code> doesn't have to be registered.
264: *
265: * @param type the certificate type
266: * @param provider the provider
267: *
268: * @return a certificate factory object for the specified type.
269: *
270: * @exception CertificateException if the certificate type is
271: * not available from the specified provider.
272: *
273: * @exception IllegalArgumentException if the <code>provider</code> is
274: * null.
275: *
276: * @see Provider
277: *
278: * @since 1.4
279: */
280: public static final CertificateFactory getInstance(String type,
281: Provider provider) throws CertificateException {
282: if (provider == null)
283: throw new IllegalArgumentException("missing provider");
284:
285: if (implMethod2Set.booleanValue() == false) {
286: synchronized (implMethod2Set) {
287: if (implMethod2Set.booleanValue() == false) {
288: implMethod2 = (Method) AccessController
289: .doPrivileged(new PrivilegedAction() {
290: public Object run() {
291: Method m = null;
292: try {
293: m = cl.getDeclaredMethod(
294: "getImpl",
295: GET_IMPL_PARAMS2);
296: if (m != null)
297: m.setAccessible(true);
298: } catch (NoSuchMethodException nsme) {
299: }
300: return m;
301: }
302: });
303: implMethod2Set = new Boolean(true);
304: }
305: }
306: }
307:
308: if (implMethod2 == null) {
309: throw new CertificateException(type + " not found");
310: }
311:
312: try {
313: // The underlying method is static, so we set the object
314: // argument to null.
315: Object[] objs = (Object[]) implMethod2
316: .invoke(null, new Object[] { type,
317: "CertificateFactory", provider });
318: return new CertificateFactory(
319: (CertificateFactorySpi) objs[0],
320: (Provider) objs[1], type);
321: } catch (IllegalAccessException iae) {
322: CertificateException ce = new CertificateException(type
323: + " not found");
324: ce.initCause(iae);
325: throw ce;
326: } catch (InvocationTargetException ite) {
327: CertificateException ce = new CertificateException(type
328: + " not found");
329: ce.initCause(ite);
330: throw ce;
331: }
332: }
333:
334: /**
335: * Returns the provider of this certificate factory.
336: *
337: * @return the provider of this certificate factory.
338: */
339: public final Provider getProvider() {
340: return this .provider;
341: }
342:
343: /**
344: * Returns the name of the certificate type associated with this
345: * certificate factory.
346: *
347: * @return the name of the certificate type associated with this
348: * certificate factory.
349: */
350: public final String getType() {
351: return this .type;
352: }
353:
354: /**
355: * Generates a certificate object and initializes it with
356: * the data read from the input stream <code>inStream</code>.
357: *
358: * <p>In order to take advantage of the specialized certificate format
359: * supported by this certificate factory,
360: * the returned certificate object can be typecast to the corresponding
361: * certificate class. For example, if this certificate
362: * factory implements X.509 certificates, the returned certificate object
363: * can be typecast to the <code>X509Certificate</code> class.
364: *
365: * <p>In the case of a certificate factory for X.509 certificates, the
366: * certificate provided in <code>inStream</code> must be DER-encoded and
367: * may be supplied in binary or printable (Base64) encoding. If the
368: * certificate is provided in Base64 encoding, it must be bounded at
369: * the beginning by -----BEGIN CERTIFICATE-----, and must be bounded at
370: * the end by -----END CERTIFICATE-----.
371: *
372: * <p>Note that if the given input stream does not support
373: * {@link java.io.InputStream#mark(int) mark} and
374: * {@link java.io.InputStream#reset() reset}, this method will
375: * consume the entire input stream. Otherwise, each call to this
376: * method consumes one certificate and the read position of the
377: * input stream is positioned to the next available byte after
378: * the inherent end-of-certificate marker. If the data in the input stream
379: * does not contain an inherent end-of-certificate marker (other
380: * than EOF) and there is trailing data after the certificate is parsed, a
381: * <code>CertificateException</code> is thrown.
382: *
383: * @param inStream an input stream with the certificate data.
384: *
385: * @return a certificate object initialized with the data
386: * from the input stream.
387: *
388: * @exception CertificateException on parsing errors.
389: */
390: public final Certificate generateCertificate(InputStream inStream)
391: throws CertificateException {
392: return certFacSpi.engineGenerateCertificate(inStream);
393: }
394:
395: /**
396: * Returns an iteration of the <code>CertPath</code> encodings supported
397: * by this certificate factory, with the default encoding first. See
398: * Appendix A in the
399: * <a href="../../../../guide/security/certpath/CertPathProgGuide.html#AppA">
400: * Java Certification Path API Programmer's Guide</a> for information about
401: * standard encoding names and their formats.
402: * <p>
403: * Attempts to modify the returned <code>Iterator</code> via its
404: * <code>remove</code> method result in an
405: * <code>UnsupportedOperationException</code>.
406: *
407: * @return an <code>Iterator</code> over the names of the supported
408: * <code>CertPath</code> encodings (as <code>String</code>s)
409: * @since 1.4
410: */
411: public final Iterator getCertPathEncodings() {
412: return (certFacSpi.engineGetCertPathEncodings());
413: }
414:
415: /**
416: * Generates a <code>CertPath</code> object and initializes it with
417: * the data read from the <code>InputStream</code> inStream. The data
418: * is assumed to be in the default encoding. The name of the default
419: * encoding is the first element of the <code>Iterator</code> returned by
420: * the {@link #getCertPathEncodings getCertPathEncodings} method.
421: *
422: * @param inStream an <code>InputStream</code> containing the data
423: * @return a <code>CertPath</code> initialized with the data from the
424: * <code>InputStream</code>
425: * @exception CertificateException if an exception occurs while decoding
426: * @since 1.4
427: */
428: public final CertPath generateCertPath(InputStream inStream)
429: throws CertificateException {
430: return (certFacSpi.engineGenerateCertPath(inStream));
431: }
432:
433: /**
434: * Generates a <code>CertPath</code> object and initializes it with
435: * the data read from the <code>InputStream</code> inStream. The data
436: * is assumed to be in the specified encoding. See Appendix A in the
437: * <a href="../../../../guide/security/certpath/CertPathProgGuide.html#AppA">
438: * Java Certification Path API Programmer's Guide</a>
439: * for information about standard encoding names and their formats.
440: *
441: * @param inStream an <code>InputStream</code> containing the data
442: * @param encoding the encoding used for the data
443: * @return a <code>CertPath</code> initialized with the data from the
444: * <code>InputStream</code>
445: * @exception CertificateException if an exception occurs while decoding or
446: * the encoding requested is not supported
447: * @since 1.4
448: */
449: public final CertPath generateCertPath(InputStream inStream,
450: String encoding) throws CertificateException {
451: return (certFacSpi.engineGenerateCertPath(inStream, encoding));
452: }
453:
454: /**
455: * Generates a <code>CertPath</code> object and initializes it with
456: * a <code>List</code> of <code>Certificate</code>s.
457: * <p>
458: * The certificates supplied must be of a type supported by the
459: * <code>CertificateFactory</code>. They will be copied out of the supplied
460: * <code>List</code> object.
461: *
462: * @param certificates a <code>List</code> of <code>Certificate</code>s
463: * @return a <code>CertPath</code> initialized with the supplied list of
464: * certificates
465: * @exception CertificateException if an exception occurs
466: * @since 1.4
467: */
468: public final CertPath generateCertPath(List certificates)
469: throws CertificateException {
470: return (certFacSpi.engineGenerateCertPath(certificates));
471: }
472:
473: /**
474: * Returns a (possibly empty) collection view of the certificates read
475: * from the given input stream <code>inStream</code>.
476: *
477: * <p>In order to take advantage of the specialized certificate format
478: * supported by this certificate factory, each element in
479: * the returned collection view can be typecast to the corresponding
480: * certificate class. For example, if this certificate
481: * factory implements X.509 certificates, the elements in the returned
482: * collection can be typecast to the <code>X509Certificate</code> class.
483: *
484: * <p>In the case of a certificate factory for X.509 certificates,
485: * <code>inStream</code> may contain a sequence of DER-encoded certificates
486: * in the formats described for
487: * {@link #generateCertificate(java.io.InputStream) generateCertificate}.
488: * In addition, <code>inStream</code> may contain a PKCS#7 certificate
489: * chain. This is a PKCS#7 <i>SignedData</i> object, with the only
490: * significant field being <i>certificates</i>. In particular, the
491: * signature and the contents are ignored. This format allows multiple
492: * certificates to be downloaded at once. If no certificates are present,
493: * an empty collection is returned.
494: *
495: * <p>Note that if the given input stream does not support
496: * {@link java.io.InputStream#mark(int) mark} and
497: * {@link java.io.InputStream#reset() reset}, this method will
498: * consume the entire input stream.
499: *
500: * @param inStream the input stream with the certificates.
501: *
502: * @return a (possibly empty) collection view of
503: * java.security.cert.Certificate objects
504: * initialized with the data from the input stream.
505: *
506: * @exception CertificateException on parsing errors.
507: */
508: public final Collection generateCertificates(InputStream inStream)
509: throws CertificateException {
510: return certFacSpi.engineGenerateCertificates(inStream);
511: }
512:
513: /**
514: * Generates a certificate revocation list (CRL) object and initializes it
515: * with the data read from the input stream <code>inStream</code>.
516: *
517: * <p>In order to take advantage of the specialized CRL format
518: * supported by this certificate factory,
519: * the returned CRL object can be typecast to the corresponding
520: * CRL class. For example, if this certificate
521: * factory implements X.509 CRLs, the returned CRL object
522: * can be typecast to the <code>X509CRL</code> class.
523: *
524: * <p>Note that if the given input stream does not support
525: * {@link java.io.InputStream#mark(int) mark} and
526: * {@link java.io.InputStream#reset() reset}, this method will
527: * consume the entire input stream. Otherwise, each call to this
528: * method consumes one CRL and the read position of the input stream
529: * is positioned to the next available byte after the the inherent
530: * end-of-CRL marker. If the data in the
531: * input stream does not contain an inherent end-of-CRL marker (other
532: * than EOF) and there is trailing data after the CRL is parsed, a
533: * <code>CRLException</code> is thrown.
534: *
535: * @param inStream an input stream with the CRL data.
536: *
537: * @return a CRL object initialized with the data
538: * from the input stream.
539: *
540: * @exception CRLException on parsing errors.
541: */
542: public final CRL generateCRL(InputStream inStream)
543: throws CRLException {
544: return certFacSpi.engineGenerateCRL(inStream);
545: }
546:
547: /**
548: * Returns a (possibly empty) collection view of the CRLs read
549: * from the given input stream <code>inStream</code>.
550: *
551: * <p>In order to take advantage of the specialized CRL format
552: * supported by this certificate factory, each element in
553: * the returned collection view can be typecast to the corresponding
554: * CRL class. For example, if this certificate
555: * factory implements X.509 CRLs, the elements in the returned
556: * collection can be typecast to the <code>X509CRL</code> class.
557: *
558: * <p>In the case of a certificate factory for X.509 CRLs,
559: * <code>inStream</code> may contain a sequence of DER-encoded CRLs.
560: * In addition, <code>inStream</code> may contain a PKCS#7 CRL
561: * set. This is a PKCS#7 <i>SignedData</i> object, with the only
562: * significant field being <i>crls</i>. In particular, the
563: * signature and the contents are ignored. This format allows multiple
564: * CRLs to be downloaded at once. If no CRLs are present,
565: * an empty collection is returned.
566: *
567: * <p>Note that if the given input stream does not support
568: * {@link java.io.InputStream#mark(int) mark} and
569: * {@link java.io.InputStream#reset() reset}, this method will
570: * consume the entire input stream.
571: *
572: * @param inStream the input stream with the CRLs.
573: *
574: * @return a (possibly empty) collection view of
575: * java.security.cert.CRL objects initialized with the data from the input
576: * stream.
577: *
578: * @exception CRLException on parsing errors.
579: */
580: public final Collection generateCRLs(InputStream inStream)
581: throws CRLException {
582: return certFacSpi.engineGenerateCRLs(inStream);
583: }
584: }
|