/*
 * @(#)X509CRL.java	1.4 97/10/17
 *
 * Copyright 1993-1997 Sun Microsystems, Inc. 901 San Antonio Road,
 * Palo Alto, California, 94303, U.S.A.  All Rights Reserved.
 *
 * This software is the confidential and proprietary information of Sun
 * Microsystems, Inc. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Sun.
 *
 * CopyrightVersion 1.2
 *
 */

package com.novell.java.security.cert;

import java.io.InputStream;
import java.lang.Class;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.security.Security;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.InvalidKeyException;
import java.security.SignatureException;

import java.math.BigInteger;
import java.security.Principal;
import java.security.PublicKey;
import java.util.BitSet;
import java.util.Date;
import com.novell.java.util.Set;

/**
 * <p>
 * Abstract class for an X.509 Certificate Revocation List (CRL).
 * A CRL is a time-stamped list identifying revoked certificates.
 * It is signed by a Certificate Authority (CA) and made freely
 * available in a public repository.
 *
 * <p>Each revoked certificate is
 * identified in a CRL by its certificate serial number. When a
 * certificate-using system uses a certificate (e.g., for verifying a
 * remote user's digital signature), that system not only checks the
 * certificate signature and validity but also acquires a suitably-
 * recent CRL and checks that the certificate serial number is not on
 * that CRL.  The meaning of "suitably-recent" may vary with local
 * policy, but it usually means the most recently-issued CRL.  A CA
 * issues a new CRL on a regular periodic basis (e.g., hourly, daily, or
 * weekly).  Entries are added to CRLs as revocations occur, and an
 * entry may be removed when the certificate expiration date is reached.
 * <p>
 * The X.509 v2 CRL format is described below in ASN.1:
 * <pre>
 * CertificateList  ::=  SEQUENCE  {
 *     tbsCertList          TBSCertList,
 *     signatureAlgorithm   AlgorithmIdentifier,
 *     signature            BIT STRING  }
 * </pre>
 * <p>
 * A good decription and profiling is provided in the IETF PKIX WG
 * draft, Part I:  X.509 Certificate and CRL Profile,
 * &lt;draft-ietf-pkix-ipki-part1-06.txt&gt;.
 * <p>
 * The ASN.1 definition of <code>tbsCertList</code> is:
 * <pre>
 * TBSCertList  ::=  SEQUENCE  {
 *     version                 Version OPTIONAL,
 *                             -- if present, must be v2
 *     signature               AlgorithmIdentifier,
 *     issuer                  Name,
 *     thisUpdate              ChoiceOfTime,
 *     nextUpdate              ChoiceOfTime OPTIONAL,
 *     revokedCertificates     SEQUENCE OF SEQUENCE  {
 *         userCertificate         CertificateSerialNumber,
 *         revocationDate          ChoiceOfTime,
 *         crlEntryExtensions      Extensions OPTIONAL
 *                                 -- if present, must be v2
 *         }  OPTIONAL,
 *     crlExtensions           [0]  EXPLICIT Extensions OPTIONAL
 *                                  -- if present, must be v2
 *     }
 * </pre>
 * <p>
 * Here is sample code to instantiate an X509CRL:
 * <pre><code>
 * InputStream inStream = new FileInputStream("fileName-of-crl");
 * X509CRL crl = X509CRL.getInstance(inStream);
 * inStream.close();
 * </code></pre>
 * OR
 * <pre><code>
 * byte[] crlData = &lt;crl read from a file, say&gt;
 * X509CRL crl = X509CRL.getInstance(crlData);
 * </code></pre>
 * <p>
 * In either case, the code that instantiates an X509CRL
 * consults the Java security properties file to locate the actual
 * implementation. The Java security properties file is located in the file
 * named &lt;JAVA_HOME&gt;/lib/security/java.security, where &lt;JAVA_HOME&gt;
 * refers to the directory where the JDK was installed.
 * In the Security properties file, the default implementation
 * for X.509 v2 CRL is given as:
 * <pre>
 * crl.provider.x509=sun.security.x509.X509CRLImpl
 * </pre>
 * <p>
 * The value of this <code>crl.provider.x509</code> property has to be
 * changed to instantiate another implementation.
 *
 * @author Hemma Prafullchandra
 * @version 1.4
 * @see X509Certificate
 */
public abstract class X509CRL implements X509Extension {

    /*
     * Constant to lookup in the Security properties file.
     * In the Security properties file the default implementation
     * for X.509 v2 CRL is given as:
     * <pre>
     * crl.provider.x509=sun.security.x509.X509CRL
     * </pre>
     */
    private static final String X509_PROVIDER = "crl.provider.x509";

    /**
     * Instantiates an X509CRL object, and initializes it with
     * the data read from the input stream <code>inStream</code>.
     * The implementation (X509CRL is an abstract class) is
     * provided by the class specified as the value of the
     * <code>crl.provider.x509</code>
     * property in the security properties file.
     *
     * <p>Note: Only one CRL is expected to be in the input stream.
     *
     * @param inStream an input stream with the data to be read to
     *        initialize the CRL.
     * @return an X509CRL object initialized with the data
     * from the input stream.
     *
     * @exception CRLException if a class initialization
     *            or CRL parsing error occurs.
     * @exception X509ExtensionException on extension parsing errors.
     */
    public static final X509CRL getInstance(InputStream inStream)
    throws CRLException, X509ExtensionException {
        return getInst((Object)inStream);
    }

    /**
     * Instantiates an X509CRL object, and initializes it with
     * the specified byte array.
     * The implementation (X509CRL is an abstract class) is
     * provided by the class specified as the value of the
     * <code>crl.provider.x509</code>
     * property in the security properties file.
     *
     * @param crlData a byte array containing the DER-encoded CRL.
     * @return an X509CRL object initialized with the data
     * from <code>crlData</code>.
     * @exception CRLException if a class initialization
     *            or CRL parsing error occurs.
     * @exception X509ExtensionException on extension parsing errors.
     */
    public static final X509CRL getInstance(byte[] crlData)
    throws CRLException, X509ExtensionException {
        return getInst((Object)crlData);
    }

    private static final X509CRL getInst(Object value)
    throws CRLException, X509ExtensionException {
        String className = Security.getProperty(X509_PROVIDER);
        if (className == null) {
            // shouldn't happen, but assume corrupted properties file
            // provide access to sun implementation
            className = "sun.security.x509.X509CRLImpl";
        }
        try {
            Class[] params = null;
            if (value instanceof InputStream) {
                params = new Class[] { InputStream.class };
            } else if (value instanceof byte[]) {
                params = new Class[] { value.getClass() };
            } else
                throw new CRLException("Unsupported arg type");
            Class certClass = Class.forName(className);

            // get the appropriate constructor and instantiate it
            Constructor cons = certClass.getConstructor(params);

            // get a new instance
            Object obj = cons.newInstance(new Object[] {value});
            return (X509CRL)obj;

        } catch (ClassNotFoundException e) {
          throw new CRLException("Could not find class: " + e);
        } catch (IllegalAccessException e) {
          throw new CRLException("Could not access class: " + e);
        } catch (InstantiationException e) {
          throw new CRLException("Problems instantiating: " + e);
        } catch (InvocationTargetException e) {
          throw new CRLException("InvocationTargetException: "
                                         + e.getTargetException());
        } catch (NoSuchMethodException e) {
          throw new CRLException("Could not find class method: "
                                          + e.getMessage());
        }
    }

    /**
     * Compares this CRL for equality with the specified
     * object. If the <code>other</code> object is an
     * <code>instanceof</code> <code>X509CRL</code>, then
     * its encoded form is retrieved and compared with the
     * encoded form of this CRL.
     *
     * @param other the object to test for equality with this CRL.
     *
     * @return true iff the encoded forms of the two CRLs
     * match, false otherwise.
     */
    public boolean equals(Object other) {
        if (this == other)
            return true;
        if (!(other instanceof X509CRL))
            return false;
        try {
            byte[] thisCRL = this.getEncoded();
            byte[] otherCRL = ((X509CRL)other).getEncoded();

            if (thisCRL.length != otherCRL.length)
                return false;
            for (int i = 0; i < thisCRL.length; i++)
                 if (thisCRL[i] != otherCRL[i])
                     return false;
            return true;
        } catch (CRLException e) {
	    return false;
        }
    }

    /**
     * Returns a hashcode value for this CRL from its
     * encoded form.
     *
     * @return the hashcode value.
     */
    public int hashCode() {
        int     retval = 0;
        try {
            byte[] crlData = this.getEncoded();
            for (int i = 1; i < crlData.length; i++) {
                 retval += crlData[i] * i;
            }
            return(retval);
        } catch (CRLException e) {
            return(retval);
        }
    }

    /**
     * Returns the ASN.1 DER-encoded form of this CRL.
     *
     * @exception CRLException if an encoding error occurs.
     */
    public abstract byte[] getEncoded()
        throws CRLException;

    /**
     * Verifies that this CRL was signed using the
     * private key that corresponds to the specified public key.
     *
     * @param key the PublicKey used to carry out the verification.
     *
     * @exception NoSuchAlgorithmException on unsupported signature
     * algorithms.
     * @exception InvalidKeyException on incorrect key.
     * @exception NoSuchProviderException if there's no default provider.
     * @exception SignatureException on signature errors.
     * @exception CRLException on encoding errors.
     */
    public abstract void verify(PublicKey key)
        throws CRLException,  NoSuchAlgorithmException,
        InvalidKeyException, NoSuchProviderException,
        SignatureException;

    /**
     * Verifies that this CRL was signed using the
     * private key that corresponds to the specified public key.
     * This method uses the signature verification engine
     * supplied by the specified provider.
     *
     * @param key the PublicKey used to carry out the verification.
     * @param sigProvider the name of the signature provider.
     *
     * @exception NoSuchAlgorithmException on unsupported signature
     * algorithms.
     * @exception InvalidKeyException on incorrect key.
     * @exception NoSuchProviderException on incorrect provider.
     * @exception SignatureException on signature errors.
     * @exception CRLException on encoding errors.
     */
    public abstract void verify(PublicKey key, String sigProvider)
        throws CRLException, NoSuchAlgorithmException,
        InvalidKeyException, NoSuchProviderException,
        SignatureException;

    /**
     * Returns a string representation of this CRL.
     *
     * @return a string representation of this CRL.
     */
    public abstract String toString();

    /**
     * Checks whether the given serial number is on this CRL.
     * Here is sample code to use this:
     * <pre><code>
     * X509Certificate cert;
     * X509CRL         crl;
     * ...
     * if (crl.isRevoked(cert.getSerialNumber()))
     *     throw new SensibleException;
     * else {
     *     doUsefulWork();
     * }
     * </code></pre>
     *
     * @param serialNumber the number to check for.
     * @return true if the given serial number is on this CRL,
     * false otherwise.
     */
    public abstract boolean isRevoked(BigInteger serialNumber);

    /**
     * Gets the <code>version</code> (version number) value from the CRL.
     * The ASN.1 definition for this is:
     * <pre>
     * version    Version OPTIONAL,
     *             -- if present, must be v2<p>
     * Version  ::=  INTEGER  {  v1(0), v2(1), v3(2)  }
     *             -- v3 does not apply to CRLs but appears for consistency
     *             -- with definition of Version for certs
     * </pre>
     *
     * @return the version number.
     */
    public abstract int getVersion();

    /**
     * Gets the <code>issuer</code> (issuer distinguished name) value from
     * the CRL. The issuer name identifies the entity that signed (and
     * issued) the CRL.
     *
     * <p>The issuer name field contains an
     * X.500 distinguished name (DN).
     * The ASN.1 definition for this is:
     * <pre>
     * issuer    Name
     *
     * Name ::= CHOICE { RDNSequence }
     * RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
     * RelativeDistinguishedName ::=
     *     SET OF AttributeValueAssertion
     *
     * AttributeValueAssertion ::= SEQUENCE {
     *                               AttributeType,
     *                               AttributeValue }
     * AttributeType ::= OBJECT IDENTIFIER
     * AttributeValue ::= ANY
     * </pre>
     * The <code>Name</code> describes a hierarchical name composed of attributes,
     * such as country name, and corresponding values, such as US.
     * The type of the <code>AttributeValue</code> component is determined by the
     * <code>AttributeType</code>; in general it will be a
     * <code>directoryString</code>. A <code>directoryString</code> is usually
     * one of <code>PrintableString</code>,
     * <code>TeletexString</code> or <code>UniversalString</code>.
     *
     * @return a Principal whose name is the issuer distinguished name.
     */
    public abstract Principal getIssuerDN();

    /**
     * Gets the <code>thisUpdate</code> date from the CRL.
     * The ASN.1 definition for this is:
     * <pre>
     * thisUpdate   ChoiceOfTime
     * ChoiceOfTime ::= CHOICE {
     *     utcTime        UTCTime,
     *     generalTime    GeneralizedTime }
     * </pre>
     *
     * @return the <code>thisUpdate</code> date from the CRL.
     */
    public abstract Date getThisUpdate();

    /**
     * Gets the <code>nextUpdate</code> date from the CRL.
     *
     * @return the <code>nextUpdate</code> date from the CRL, or null if
     * not present.
     */
    public abstract Date getNextUpdate();

    /**
     * Gets the revoked certificate with serial number
     * <code>serialNumber</code> from the CRL.
     *
     * @return the revoked certificate, or null if there is
     * no entry in the CRL marked with the provided serial number.
     * @see RevokedCertificate
     */
    public abstract RevokedCertificate
        getRevokedCertificate(BigInteger serialNumber);

    /**
     * Gets all the revoked certificates from the CRL.
     * This returns a Set of RevokedCertificate objects.
     *
     * @return all the revoked certificates or null if there
     * are none present.
     * @see RevokedCertificate
     */
    public abstract Set getRevokedCertificates();

    /**
     * Gets the DER-encoded CRL information, the
     * <code>tbsCertList</code> from this CRL.
     * This can be used to verify the signature independently.
     *
     * @return the DER-encoded CRL information.
     * @exception CRLException if a parsing error occurs.
     * @exception X509ExtensionException on extension parsing errors.
     */
    public abstract byte[] getTBSCertList()
        throws CRLException, X509ExtensionException;

    /**
     * Gets the <code>signature</code> value (the raw signature bits) from
     * the CRL.
     * The ASN.1 definition for this is:
     * <pre>
     * signature     BIT STRING
     * </pre>
     *
     * @return the signature.
     */
    public abstract byte[] getSignature();

    /**
     * Gets the signature algorithm name for the CRL
     * signature algorithm. An example is the string "SHA-1/DSA".
     * The ASN.1 definition for this is:
     * <pre>
     * signatureAlgorithm   AlgorithmIdentifier<p>
     * AlgorithmIdentifier  ::=  SEQUENCE  {
     *     algorithm               OBJECT IDENTIFIER,
     *     parameters              ANY DEFINED BY algorithm OPTIONAL  }
     *                             -- contains a value of the type
     *                             -- registered for use with the
     *                             -- algorithm object identifier value
     * </pre>
     *
     * <p>The algorithm name is determined from the <code>algorithm</code>
     * OID string.
     *
     * @return the signature algorithm name.
     */
    public abstract String getSigAlgName();

    /**
     * Gets the signature algorithm OID string from the CRL.
     * An OID is represented by a set of positive whole numbers separated
     * by periods.
     * For example, the string "1.2.840.10040.4.3" identifies the SHA-1
     * with DSA signature algorithm, as per the PKIX part I.
     *
     * <p>See <a href = "#getSigAlgName">getSigAlgName</a> for
     * relevant ASN.1 definitions.
     *
     * @return the signature algorithm OID string.
     */
    public abstract String getSigAlgOID();

    /**
     * Gets the DER-encoded signature algorithm parameters from this
     * CRL's signature algorithm. In most cases, the signature
     * algorithm parameters are null; the parameters are usually
     * supplied with the public key.
     * If access to individual parameter values is needed then use
     * <a href="java.security.AlgorithmParameters.html">
     * AlgorithmParameters</a>
     * and instantiate with the name returned by
     * <a href = "#getSigAlgName">getSigAlgName</a>.
     *
     * <p>See <a href = "#getSigAlgName">getSigAlgName</a> for
     * relevant ASN.1 definitions.
     *
     * @return the DER-encoded signature algorithm parameters, or
     *         null if no parameters are present.
     */
    public abstract byte[] getSigAlgParams();
}
