//////////////////////////////////////////////////////////////////////////// 
// 
// Copyright (C) DSTC Pty Ltd (ACN 052 372 577) 1993, 1994, 1995.
// Unpublished work.  All Rights Reserved.
// 
// The software contained on this media is the property of the
// DSTC Pty Ltd.  Use of this software is strictly in accordance
// with the license agreement in the accompanying LICENSE.DOC 
// file. If your distribution of this software does not contain 
// a LICENSE.DOC file then you have no rights to use this 
// software in any manner and should contact DSTC at the address 
// below to determine an appropriate licensing arrangement.
// 
//      DSTC Pty Ltd
//      Level 7, GP South
//      University of Queensland
//      St Lucia, 4072
//      Australia
//      Tel: +61 7 3365 4310
//      Fax: +61 7 3365 4311
//      Email: jcsi@dstc.qut.edu.au
// 
// This software is being provided "AS IS" without warranty of
// any kind.  In no event shall DSTC Pty Ltd be liable for
// damage of any kind arising out of or in connection with
// the use or performance of this software.
// 
//////////////////////////////////////////////////////////////////////////// 

package jcsi.servlet;

import java.util.Set;
import java.util.HashSet;
import java.util.Vector;

import java.io.*;
import java.util.Properties;
import java.util.Calendar;
import java.util.Hashtable;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.BasicAttribute;

import java.math.BigInteger;
import java.security.*;
import java.security.spec.*;
import java.security.cert.*;
import com.dstc.security.asn1.*;
import com.dstc.security.pki.*;
import com.dstc.security.pki.netscape.NetscapeCertificationRequest;
import com.dstc.security.x509.extns.*;
import com.dstc.security.x509.Base64InputStream;
import com.dstc.security.x509.Base64OutputStream;

/**
 * A servlet which returns a user certificate from a Netscape
 * certification request 
 *
 * @version 0.98, 99/02/15
 * @author Ming Yung
 */
public class NetscapeServlet extends OnlineCAServlet
{
  protected X509Certificate processCertRequest(HttpServletRequest req, 
                                               HttpServletResponse res)
    throws ServletException, IOException
  {
    try
    {
      //set the "content type" header of the response
      res.setContentType("application/x-x509-user-cert");

      X509Certificate cert = processNetscape(req);

      // then write the data of the response
      Base64OutputStream bos
        = new Base64OutputStream(res.getOutputStream(),
                                 "-----BEGIN CERTIFICATE-----",
                                 "-----END CERTIFICATE-----");
      bos.write(cert.getEncoded());
      bos.flush();
      return cert;
    }
    catch (CertificateException e)
    {
      throw new ServletException(e.getMessage());
    }
  }

  private X509Certificate processNetscape(HttpServletRequest req)
    throws ServletException, IOException
  {
    try 
    {
      InputStream b64is = 
        new ByteArrayInputStream(req.getParameter("public_key").getBytes());

      InputStream is = new Base64InputStream(b64is, null, null);
      byte encoded[] = new byte[is.available()];
      is.read(encoded);

      NetscapeCertificationRequest certReq
        = (NetscapeCertificationRequest)
            CertRequestFactory.getRequest("Netscape", encoded);

      //Extract the public key from the request

      KeyFactory keyFact 
        = KeyFactory.getInstance(certReq.getKeyAlgName());

      PublicKey subjectPub
        = keyFact.generatePublic(new X509EncodedKeySpec(
           certReq.getSubjectPublicKeyInfo().encode()));
      caTool.setSubjectPubKey(subjectPub);

      BigInteger serialNumber =
        BigInteger.valueOf(Calendar.getInstance().getTime().getTime());

      //Extract identifying info from browser request

      String commonName = req.getParameterValues("common_name")[0];

      String dept = req.getParameterValues("organizational_unit")[0];
      String org = req.getParameterValues("organization")[0];
      String country = req.getParameterValues("country")[0];

      StringBuffer sb = new StringBuffer();
      sb.append("CN=").append(commonName);
      sb.append(", OU=").append(dept);
      sb.append(", O=").append(org);
      sb.append(", C=").append(country);
      this.entryName = sb.toString();

      String email = req.getParameterValues("email_address")[0];
      caTool.setEmail(email);

/*
      StringBuffer subjectDN = new StringBuffer();
      subjectDN.append("2.5.4.3=").append(commonName).append(", ");
      subjectDN.append("2.5.4.11=").append(dept).append(", ");
      subjectDN.append("2.5.4.10=").append(org).append(", ");
      subjectDN.append("2.5.4.6=").append(country);

      caTool.setSubjectDN(subjectDN.toString());
*/
      caTool.setSubjectDN(this.entryName);

      caTool.addExtension(new NetscapeCertType(true, 
        (byte)(NetscapeCertType.SMIME | NetscapeCertType.SSL_CLIENT)));

      X509Certificate cert 
        = (X509Certificate) caTool.generateCertificate(2, serialNumber);

      return cert;
    } 
    catch(com.dstc.security.asn1.Asn1Exception e) 
    {
      e.printStackTrace();
      return null;
    } 
    catch(Exception e) 
    {
      e.printStackTrace();
      return null;
    }
  }
}
