home *** CD-ROM | disk | FTP | other *** search
/ Java 1.2 How-To / JavaHowTo.iso / 3rdParty / jbuilder / unsupported / JDK1.2beta3 / SOURCE / SRC.ZIP / java / security / cert / X509Certificate.java < prev    next >
Encoding:
Java Source  |  1998-03-20  |  20.6 KB  |  552 lines

  1. /*
  2.  * @(#)X509Certificate.java    1.14 98/03/18
  3.  *
  4.  * Copyright 1997, 1998 by Sun Microsystems, Inc.,
  5.  * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A.
  6.  * All rights reserved.
  7.  *
  8.  * This software is the confidential and proprietary information
  9.  * of Sun Microsystems, Inc. ("Confidential Information").  You
  10.  * shall not disclose such Confidential Information and shall use
  11.  * it only in accordance with the terms of the license agreement
  12.  * you entered into with Sun.
  13.  */
  14.  
  15. package java.security.cert;
  16.  
  17. import java.io.InputStream;
  18. import java.lang.Class;
  19. import java.lang.reflect.Constructor;
  20. import java.lang.reflect.InvocationTargetException;
  21. import java.security.Security;
  22.  
  23. import java.math.BigInteger;
  24. import java.security.Principal;
  25. import java.security.PublicKey;
  26. import java.util.BitSet;
  27. import java.util.Date;
  28. import java.util.Set;
  29.  
  30. /**
  31.  * <p>
  32.  * Abstract class for X.509 certificates. This provides a standard
  33.  * way to access all the attributes of an X.509 certificate.
  34.  * <p>
  35.  * In June of 1996, the basic X.509 v3 format was completed by
  36.  * ISO/IEC and ANSI X9, which is described below in ASN.1:
  37.  * <pre>
  38.  * Certificate  ::=  SEQUENCE  {
  39.  *     tbsCertificate       TBSCertificate,
  40.  *     signatureAlgorithm   AlgorithmIdentifier,
  41.  *     signature            BIT STRING  }
  42.  * </pre>
  43.  * <p>
  44.  * These certificates are widely used to support authentication and
  45.  * other functionality in Internet security systems. Common applications
  46.  * include Privacy Enhanced Mail (PEM), Transport Layer Security (SSL),
  47.  * code signing for trusted software distribution, and Secure Electronic
  48.  * Transactions (SET).
  49.  * <p>
  50.  * These certificates are managed and vouched for by <em>Certificate
  51.  * Authorities</em> (CAs). CAs are services which create certificates by
  52.  * placing data in the X.509 standard format and then digitally signing
  53.  * that data. CAs act as trusted third parties, making introductions
  54.  * between principals who have no direct knowledge of each other.
  55.  * CA certificates are either signed by themselves, or by some other
  56.  * CA such as a "root" CA.
  57.  * <p>
  58.  * A good decription and profiling is provided in the IETF PKIX WG
  59.  * draft, Part I:  X.509 Certificate and CRL Profile,
  60.  * <draft-ietf-pkix-ipki-part1-06.txt>.
  61.  * <p>
  62.  * The ASN.1 definition of <code>tbsCertificate</code> is:
  63.  * <pre>
  64.  * TBSCertificate  ::=  SEQUENCE  {
  65.  *     version         [0]  EXPLICIT Version DEFAULT v1,
  66.  *     serialNumber         CertificateSerialNumber,
  67.  *     signature            AlgorithmIdentifier,
  68.  *     issuer               Name,
  69.  *     validity             Validity,
  70.  *     subject              Name,
  71.  *     subjectPublicKeyInfo SubjectPublicKeyInfo,
  72.  *     issuerUniqueID  [1]  IMPLICIT UniqueIdentifier OPTIONAL,
  73.  *                          -- If present, version must be v2 or v3
  74.  *     subjectUniqueID [2]  IMPLICIT UniqueIdentifier OPTIONAL,
  75.  *                          -- If present, version must be v2 or v3
  76.  *     extensions      [3]  EXPLICIT Extensions OPTIONAL
  77.  *                          -- If present, version must be v3
  78.  *     }
  79.  * </pre>
  80.  * <p>
  81.  * Here is sample code to instantiate an X.509 certificate:
  82.  * <pre> 
  83.  * InputStream inStream = new FileInputStream("fileName-of-cert");
  84.  * X509Certificate cert = X509Certificate.getInstance(inStream);
  85.  * inStream.close();
  86.  * </pre>
  87.  * OR
  88.  * <pre>
  89.  * byte[] certData = <certificate read from a file, say>
  90.  * X509Certificate cert = X509Certificate.getInstance(certData);
  91.  * </pre>
  92.  * <p>
  93.  * In either case, the code that instantiates an X.509 certificate
  94.  * consults the Java security properties file to locate the actual
  95.  * implementation.  The default implementation for the
  96.  * <code>java.security.cert</code> package is the Sun X.509 v3 
  97.  * implementation, from what is known to the <code>java.security</code>
  98.  * APIs as the "SUN" provider.
  99.  * 
  100.  * <p>
  101.  * The Java security properties file is located in the file named
  102.  * <JAVA_HOME>/lib/security/java.security, where <JAVA_HOME>
  103.  * refers to the directory where the JDK was installed.
  104.  * In the Security properties file, the default implementation
  105.  * for X.509 v3 is given as:
  106.  * <pre>
  107.  * cert.provider.x509=sun.security.x509.X509CertImpl
  108.  * </pre>
  109.  * <p>
  110.  * The value of this <code>cert.provider.x509</code> property has to be 
  111.  * changed to instatiate another implementation.
  112.  *
  113.  * @author Hemma Prafullchandra
  114.  * @version 1.14
  115.  * @see Certificate
  116.  * @see X509Extension
  117.  */
  118. public abstract class X509Certificate extends Certificate
  119. implements X509Extension {
  120.  
  121.     /*
  122.      * Constant to lookup in the Security properties file.
  123.      * In the Security properties file the default implementation
  124.      * for X.509 v3 is given as:
  125.      * <pre>
  126.      * cert.provider.x509=sun.security.x509.X509CertImpl
  127.      * </pre>
  128.      */  
  129.     private static final String X509_PROVIDER = "cert.provider.x509";
  130.     
  131.     /**
  132.      * Instantiates an X509Certificate object, and initializes it with
  133.      * the data read from the input stream <code>inStream</code>.
  134.      * The implementation (X509Certificate is an abstract class) is
  135.      * provided by the class specified as the value of the 
  136.      * <code>cert.provider.x509</code>
  137.      * property in the security properties file.
  138.      *
  139.      * <p>Note: Only one DER-encoded
  140.      * certificate is expected to be in the input stream.
  141.      * Also, all X509Certificate
  142.      * subclasses must provide a constructor of the form:
  143.      * <code><pre>
  144.      * public <subClass>(InputStream inStream) ...
  145.      * </code></pre>
  146.      *   
  147.      * @param inStream an input stream with the data to be read to
  148.      *        initialize the certificate.
  149.      * @return an X509Certificate object initialized with the data
  150.      * from the input stream.
  151.      * @exception CertificateException if a class initialization
  152.      *            or certificate parsing error occurs.
  153.      */
  154.     public static final X509Certificate getInstance(InputStream inStream)
  155.     throws CertificateException {
  156.         return getInst((Object)inStream);
  157.     }
  158.  
  159.     /**
  160.      * Instantiates an X509Certificate object, and initializes it with
  161.      * the specified byte array.
  162.      * The implementation (X509Certificate is an abstract class) is
  163.      * provided by the class specified as the value of the 
  164.      * <code>cert.provider.x509</code>
  165.      * property in the security properties file.
  166.      *
  167.      * <p>Note: All X509Certificate
  168.      * subclasses must provide a constructor of the form:
  169.      * <code><pre>
  170.      * public <subClass>(InputStream inStream) ...
  171.      * </code></pre>
  172.      *   
  173.      * @param certData a byte array containing the DER-encoded
  174.      * certificate.
  175.      * @return an X509Certificate object initialized with the data
  176.      * from <code>certData</code>.
  177.      * @exception CertificateException if a class initialization
  178.      *            or certificate parsing error occurs.
  179.      */
  180.     public static final X509Certificate getInstance(byte[] certData)
  181.     throws CertificateException {
  182.         return getInst((Object)certData);
  183.     }
  184.  
  185.     private static final X509Certificate getInst(Object value)
  186.     throws CertificateException {
  187.         String className = null;
  188.  
  189.     try {
  190.         java.security.AccessController.beginPrivileged();
  191.         className = Security.getProperty(X509_PROVIDER);
  192.     } finally {
  193.         java.security.AccessController.endPrivileged();
  194.     }
  195.  
  196.         if (className == null) {
  197.             // shouldn't happen, but assume corrupted properties file
  198.             // provide access to sun implementation
  199.             className = "sun.security.x509.X509CertImpl";
  200.         }
  201.         try {
  202.             Class[] params = null;
  203.             if (value instanceof InputStream) {
  204.                 params = new Class[] { InputStream.class };
  205.             } else if (value instanceof byte[]) {
  206.                 params = new Class[] { value.getClass() };
  207.             } else
  208.                 throw new CertificateException("Unsupported argument type");
  209.             Class certClass = Class.forName(className);
  210.  
  211.             // get the appropriate constructor and instantiate it
  212.             Constructor cons = certClass.getConstructor(params);
  213.  
  214.             // get a new instance
  215.             Object obj = cons.newInstance(new Object[] {value});
  216.             return (X509Certificate)obj;
  217.  
  218.         } catch (ClassNotFoundException e) {
  219.           throw new CertificateException("Could not find class: " + e);
  220.         } catch (IllegalAccessException e) {
  221.           throw new CertificateException("Could not access class: " + e);
  222.         } catch (InstantiationException e) {
  223.           throw new CertificateException("Problems instantiating: " + e);
  224.         } catch (InvocationTargetException e) {
  225.           throw new CertificateException("InvocationTargetException: "
  226.                                          + e.getTargetException());
  227.        } catch (NoSuchMethodException e) {
  228.           throw new CertificateException("Could not find class method: "
  229.                                           + e.getMessage());
  230.         }
  231.     }
  232.  
  233.     /**
  234.      * Checks that the certificate is currently valid. It is if
  235.      * the current date and time are within the validity period given in the
  236.      * certificate.
  237.      * <p>
  238.      * The validity period consists of two date/time values: 
  239.      * the first and last dates (and times) on which the certificate 
  240.      * is valid. It is defined in
  241.      * ASN.1 as:
  242.      * <pre>
  243.      * validity             Validity<p>
  244.      * Validity ::= SEQUENCE {
  245.      *     notBefore      CertificateValidityDate,
  246.      *     notAfter       CertificateValidityDate }<p>
  247.      * CertificateValidityDate ::= CHOICE {
  248.      *     utcTime        UTCTime,
  249.      *     generalTime    GeneralizedTime }
  250.      * </pre>
  251.      * 
  252.      * @exception CertificateExpiredException if the certificate has expired.
  253.      * @exception CertificateNotYetValidException if the certificate is not
  254.      * yet valid.
  255.      */
  256.     public abstract void checkValidity()
  257.         throws CertificateExpiredException, CertificateNotYetValidException;
  258.  
  259.     /**
  260.      * Checks that the specified date is within the certificate's
  261.      * validity period. In other words, this determines whether the 
  262.      * certificate would be valid at the specified date/time.
  263.      *
  264.      * @param date the Date to check against to see if this certificate
  265.      *        is valid at that date/time.
  266.      *
  267.      * @exception CertificateExpiredException if the certificate has expired
  268.      * with respect to the <code>date</code> supplied.
  269.      * @exception CertificateNotYetValidException if the certificate is not
  270.      * yet valid with respect to the <code>date</code> supplied.
  271.      * 
  272.      * @see #checkValidity()
  273.      */
  274.     public abstract void checkValidity(Date date)
  275.         throws CertificateExpiredException, CertificateNotYetValidException;
  276.  
  277.     /**
  278.      * Gets the <code>version</code> (version number) value from the certificate.
  279.      * The ASN.1 definition for this is:
  280.      * <pre>
  281.      * version         [0]  EXPLICIT Version DEFAULT v1<p>
  282.      * Version  ::=  INTEGER  {  v1(0), v2(1), v3(2)  }
  283.      * </pre>
  284.      * @return the version number.
  285.      */
  286.     public abstract int getVersion();
  287.  
  288.     /**
  289.      * Gets the <code>serialNumber</code> value from the certificate.
  290.      * The serial number is an integer assigned by the certification
  291.      * authority to each certificate. It must be unique for each
  292.      * certificate issued by a given CA (i.e., the issuer name and
  293.      * serial number identify a unique certificate).
  294.      * The ASN.1 definition for this is:
  295.      * <pre>
  296.      * serialNumber     CertificateSerialNumber<p>
  297.      * 
  298.      * CertificateSerialNumber  ::=  INTEGER
  299.      * </pre>
  300.      *
  301.      * @return the serial number.
  302.      */
  303.     public abstract BigInteger getSerialNumber();
  304.  
  305.     /**
  306.      * Gets the <code>issuer</code> (issuer distinguished name) value from 
  307.      * the certificate. The issuer name identifies the entity that signed (and
  308.      * issued) the certificate. 
  309.      * 
  310.      * <p>The issuer name field contains an
  311.      * X.500 distinguished name (DN).
  312.      * The ASN.1 definition for this is:
  313.      * <pre>
  314.      * issuer    Name<p>
  315.      *
  316.      * Name ::= CHOICE { RDNSequence }
  317.      * RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
  318.      * RelativeDistinguishedName ::=
  319.      *     SET OF AttributeValueAssertion
  320.      *
  321.      * AttributeValueAssertion ::= SEQUENCE {
  322.      *                               AttributeType,
  323.      *                               AttributeValue }
  324.      * AttributeType ::= OBJECT IDENTIFIER
  325.      * AttributeValue ::= ANY
  326.      * </pre>
  327.      * The <code>Name</code> describes a hierarchical name composed of attributes,
  328.      * such as country name, and corresponding values, such as US.
  329.      * The type of the <code>AttributeValue</code> component is determined by the
  330.      * <code>AttributeType</code>; in general it will be a 
  331.      * <code>directoryString</code>. A <code>directoryString</code> is usually 
  332.      * one of <code>PrintableString</code>,
  333.      * <code>TeletexString</code> or <code>UniversalString</code>.
  334.      * 
  335.      * @return a Principal whose name is the issuer distinguished name.
  336.      */
  337.     public abstract Principal getIssuerDN();
  338.  
  339.     /**
  340.      * Gets the <code>subject</code> (subject distinguished name) value 
  341.      * from the certificate.
  342.      * The ASN.1 definition for this is:
  343.      * <pre>
  344.      * subject    Name
  345.      * </pre>
  346.      * 
  347.      * <p>See <a href = "#getIssuerDN">getIssuerDN</a> for <code>Name</code> 
  348.      * and other relevant definitions.
  349.      * 
  350.      * @return a Principal whose name is the subject name.
  351.      */
  352.     public abstract Principal getSubjectDN();
  353.  
  354.     /**
  355.      * Gets the <code>notBefore</code> date from the validity period of 
  356.      * the certificate.
  357.      * The relevant ASN.1 definitions are:
  358.      * <pre>
  359.      * validity             Validity<p>
  360.      * 
  361.      * Validity ::= SEQUENCE {
  362.      *     notBefore      CertificateValidityDate,
  363.      *     notAfter       CertificateValidityDate }<p>
  364.      * CertificateValidityDate ::= CHOICE {
  365.      *     utcTime        UTCTime,
  366.      *     generalTime    GeneralizedTime }
  367.      * </pre>
  368.      *
  369.      * @return the start date of the validity period.
  370.      * @see #checkValidity
  371.      */
  372.     public abstract Date getNotBefore();
  373.  
  374.     /**
  375.      * Gets the <code>notAfter</code> date from the validity period of 
  376.      * the certificate. See <a href = "#getNotBefore">getNotBefore</a>
  377.      * for relevant ASN.1 definitions.
  378.      *
  379.      * @return the end date of the validity period.
  380.      * @see #checkValidity
  381.      */
  382.     public abstract Date getNotAfter();
  383.  
  384.     /**
  385.      * Gets the DER-encoded certificate information, the
  386.      * <code>tbsCertificate</code> from this certificate.
  387.      * This can be used to verify the signature independently.
  388.      *
  389.      * @return the DER-encoded certificate information.
  390.      * @exception CertificateEncodingException if an encoding error occurs.
  391.      */
  392.     public abstract byte[] getTBSCertificate()
  393.         throws CertificateEncodingException;
  394.  
  395.     /**
  396.      * Gets the <code>signature</code> value (the raw signature bits) from 
  397.      * the certificate.
  398.      * The ASN.1 definition for this is:
  399.      * <pre>
  400.      * signature     BIT STRING  
  401.      * </pre>
  402.      *
  403.      * @return the signature.
  404.      */
  405.     public abstract byte[] getSignature();
  406.  
  407.     /**
  408.      * Gets the signature algorithm name for the certificate
  409.      * signature algorithm. An example is the string "SHA-1/DSA".
  410.      * The ASN.1 definition for this is:
  411.      * <pre>
  412.      * signatureAlgorithm   AlgorithmIdentifier<p>
  413.      * AlgorithmIdentifier  ::=  SEQUENCE  {
  414.      *     algorithm               OBJECT IDENTIFIER,
  415.      *     parameters              ANY DEFINED BY algorithm OPTIONAL  }
  416.      *                             -- contains a value of the type
  417.      *                             -- registered for use with the
  418.      *                             -- algorithm object identifier value
  419.      * </pre>
  420.      * 
  421.      * <p>The algorithm name is determined from the <code>algorithm</code>
  422.      * OID string.
  423.      *
  424.      * @return the signature algorithm name.
  425.      */
  426.     public abstract String getSigAlgName();
  427.  
  428.     /**
  429.      * Gets the signature algorithm OID string from the certificate.
  430.      * An OID is represented by a set of positive whole numbers separated
  431.      * by periods.
  432.      * For example, the string "1.2.840.10040.4.3" identifies the SHA-1
  433.      * with DSA signature algorithm, as per the PKIX part I.
  434.      * 
  435.      * <p>See <a href = "#getSigAlgName">getSigAlgName</a> for 
  436.      * relevant ASN.1 definitions.
  437.      *
  438.      * @return the signature algorithm OID string.
  439.      */
  440.     public abstract String getSigAlgOID();
  441.  
  442.     /**
  443.      * Gets the DER-encoded signature algorithm parameters from this
  444.      * certificate's signature algorithm. In most cases, the signature
  445.      * algorithm parameters are null; the parameters are usually
  446.      * supplied with the certificate's public key.
  447.      * If access to individual parameter values is needed then use
  448.      * <a href="java.security.AlgorithmParameters.html">
  449.      * AlgorithmParameters</a>
  450.      * and instantiate with the name returned by
  451.      * <a href = "#getSigAlgName">getSigAlgName</a>.
  452.      * 
  453.      * <p>See <a href = "#getSigAlgName">getSigAlgName</a> for 
  454.      * relevant ASN.1 definitions.
  455.      *
  456.      * @return the DER-encoded signature algorithm parameters, or
  457.      *         null if no parameters are present.
  458.      */
  459.     public abstract byte[] getSigAlgParams();
  460.  
  461.     /**
  462.      * Gets the <code>issuerUniqueID</code> value from the certificate.
  463.      * The issuer unique identifier is present in the certificate
  464.      * to handle the possibility of reuse of issuer names over time.
  465.      * The PKIX Part I recommends that names not be reused and that
  466.      * conforming certificates not make use of unique identifiers.
  467.      * Applications conforming to that profile should be capable of
  468.      * parsing unique identifiers and making comparisons.
  469.      * 
  470.      * <p>The ASN.1 definition for this is:
  471.      * <pre>
  472.      * issuerUniqueID  [1]  IMPLICIT UniqueIdentifier OPTIONAL<p>
  473.      * UniqueIdentifier  ::=  BIT STRING
  474.      * </pre>
  475.      *
  476.      * @return the issuer unique identifier or null if it is not
  477.      * present in the certificate.
  478.      */
  479.     public abstract boolean[] getIssuerUniqueID();
  480.  
  481.     /**
  482.      * Gets the <code>subjectUniqueID</code> value from the certificate.
  483.      * 
  484.      * <p>The ASN.1 definition for this is:
  485.      * <pre>
  486.      * subjectUniqueID  [2]  IMPLICIT UniqueIdentifier OPTIONAL<p>
  487.      * UniqueIdentifier  ::=  BIT STRING
  488.      * </pre>
  489.      *
  490.      * @return the subject unique identifier or null if it is not
  491.      * present in the certificate.
  492.      */
  493.     public abstract boolean[] getSubjectUniqueID();
  494.    
  495.     /**
  496.      * Gets a boolean array representing bits of
  497.      * the <code>KeyUsage</code> extension, (OID = 2.5.29.15).
  498.      * The key usage extension defines the purpose (e.g., encipherment,
  499.      * signature, certificate signing) of the key contained in the
  500.      * certificate.
  501.      * The ASN.1 definition for this is:
  502.      * <pre>
  503.      * KeyUsage ::= BIT STRING {
  504.      *     digitalSignature        (0),
  505.      *     nonRepudiation          (1),
  506.      *     keyEncipherment         (2),
  507.      *     dataEncipherment        (3),
  508.      *     keyAgreement            (4),
  509.      *     keyCertSign             (5),
  510.      *     cRLSign                 (6),
  511.      *     encipherOnly            (7),
  512.      *     decipherOnly            (8) }
  513.      * </pre>
  514.      * The PKIX part I draft recommends that when used, this be marked
  515.      * as a critical extension.
  516.      *
  517.      * @return the bit values of the KeyUsage extension as an array of booleans,
  518.      * or null if the KeyUsage extension is not present in the certificate.
  519.      */
  520.     public abstract boolean[] getKeyUsage();
  521.  
  522.     /**
  523.      * Gets the certificate constraints path length from the
  524.      * critical <code>BasicConstraints</code> extension, (OID = 2.5.29.19).
  525.      * <p>
  526.      * The basic constraints extension identifies whether the subject
  527.      * of the certificate is a Certificate Authority (CA) and 
  528.      * how deep a certification path may exist through that CA. The 
  529.      * <code>pathLenConstraint</code> field (see below) is meaningful
  530.      * only if <code>cA</code> is set to TRUE. In this case, it gives the maximum
  531.      * number of CA certificates that may follow this certificate in a
  532.      * certification path. A value of zero indicates that only an end-entity
  533.      * certificate may follow in the path.
  534.      * <p>
  535.      * Note that for the PKIX profile this extension is always marked
  536.      * critical if <code>cA</code> is TRUE, meaning this certificate belongs
  537.      * to a Certificate Authority.
  538.      * <p>
  539.      * The ASN.1 definition for this is:
  540.      * <pre>
  541.      * BasicConstraints ::= SEQUENCE {
  542.      *     cA                  BOOLEAN DEFAULT FALSE,
  543.      *     pathLenConstraint   INTEGER (0..MAX) OPTIONAL }
  544.      * </pre>
  545.      *
  546.      * @return the length of the constraint if the BasicConstraints extension is
  547.      * present in the certificate and the <code>cA</code> value is TRUE. 
  548.      * Otherwise returns -1.
  549.      */
  550.     public abstract int getBasicConstraints();
  551. }
  552.