package org.bouncycastle.ocsp;

import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.IOException;
import java.security.NoSuchProviderException;
import java.security.PublicKey;

import org.bouncycastle.asn1.ASN1OutputStream;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.ocsp.OCSPRequest;
import org.bouncycastle.asn1.ocsp.Request;
import org.bouncycastle.asn1.x509.GeneralName;
import org.bouncycastle.asn1.x509.X509Extensions;

import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.Enumeration;

public class OCSPReq
{
    private OCSPRequest req;
    private X509Certificate[]   chain = null;

    public OCSPReq(
        OCSPRequest req)
    {
        this.req = req;
    }
    
    public OCSPReq(
        byte[]          req)
        throws IOException
    {
        this(new ByteArrayInputStream(req));
    }

    public OCSPReq(
        InputStream     in)
        throws IOException
    {
        this.req = OCSPRequest.getInstance(
                        new ASN1InputStream(in).readObject());
    }
    

	public int getVersion()
	{
		return req.getTbsRequest().getVersion().getValue().intValue() + 1;
	}

	public GeneralName getRequestorName()
	{
		return GeneralName.getInstance(req.getTbsRequest().getRequestorName());
	}

	public Req[] getRequestList()
	{
        ASN1Sequence    seq = req.getTbsRequest().getRequestList();
        Req[]   requests = new Req[seq.size()];

        for (int i = 0; i != requests.length; i++)
        {
            requests[i] = new Req(Request.getInstance(seq.getObjectAt(i)));
        }

		return requests;
	}

	public X509Extensions getRequestExtensions()
	{
		return X509Extensions.getInstance(req.getTbsRequest().getRequestExtensions());
	}

    /**
     * return the object identifier representing the signature algorithm
     */
    public String getSignatureAlgOID()
    {
        if (!this.isSigned())
        {
            return null;
        }

		return req.getOptionalSignature().getSignatureAlgorithm().getObjectId().getId();
    }

    public byte[] getSignature()
    {
        if (!this.isSigned())
        {
            return null;
        }

		return req.getOptionalSignature().getSignature().getBytes();
    }
    
	public X509Certificate[] getCerts(
		String  provider)
		throws OCSPException, NoSuchProviderException
	{
		if (!this.isSigned())
		{
			return null;
		}
	
		if (chain == null)
		{
			ArrayList               			certs = new ArrayList();
			ByteArrayOutputStream	bOut = new ByteArrayOutputStream();
			ASN1OutputStream        	aOut = new ASN1OutputStream(bOut);
			CertificateFactory      		cf;

			try
			{
				cf = CertificateFactory.getInstance("X.509", provider);
			}
			catch (CertificateException ex)
			{
				throw new OCSPException("can't get certificate factory.", ex);
			}

			//
			// load the certificates and revocation lists if we have any
			//
			ASN1Sequence s = req.getOptionalSignature().getCerts();

			if (s != null)
			{
				Enumeration e = s.getObjects();

				while (e.hasMoreElements())
				{
					try
					{
						aOut.writeObject(e.nextElement());

						certs.add(cf.generateCertificate(
							new ByteArrayInputStream(bOut.toByteArray())));
					}
					catch (IOException ex)
					{
						throw new OCSPException(
								"can't re-encode certificate!", ex);
					}
					catch (CertificateException ex)
					{
						throw new OCSPException(
								"can't re-encode certificate!", ex);
					}

					bOut.reset();
				}
			}

			chain = (X509Certificate[])certs.toArray(new X509Certificate[certs.size()]);
		}

		return chain;
	}
	
    public boolean isSigned()
    {
        return req.getOptionalSignature() != null;
    }

    /**
     * verify the signature against the TBSRequest object we contain.
     */
    public boolean verify(
        PublicKey   key,
        String      sigProvider)
        throws OCSPException, NoSuchProviderException
    {
        if (!this.isSigned())
        {
            throw new OCSPException("attempt to verify signature on unsigned object");
        }

        try
        {
            java.security.Signature signature = java.security.Signature.getInstance(this.getSignatureAlgOID(), sigProvider);

            signature.initVerify(key);

            ByteArrayOutputStream   bOut = new ByteArrayOutputStream();
            ASN1OutputStream        aOut = new ASN1OutputStream(bOut);

            aOut.writeObject(req.getTbsRequest());

            signature.update(bOut.toByteArray());

            return signature.verify(this.getSignature());
        }
        catch (NoSuchProviderException e)
        {
            throw e;
        }
        catch (Exception e)
        {
            throw new OCSPException("exception processing sig: " + e, e);
        }
    }

    /**
     * return the ASN.1 encoded representation of this object.
     */
    public byte[] getEncoded()
        throws IOException
    {
        ByteArrayOutputStream   bOut = new ByteArrayOutputStream();
        ASN1OutputStream        aOut = new ASN1OutputStream(bOut);

        aOut.writeObject(req);

        return bOut.toByteArray();
    }
}
