/*
 * JBoss, the OpenSource J2EE webOS
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 *
 * Created on Jan 20, 2004
 */
package org.jboss.net.axis.security;

import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.Enumeration;
import java.util.Properties;

import javax.security.auth.x500.X500Principal;

import org.apache.log4j.Logger;
import org.apache.ws.security.components.crypto.Merlin;

/**
 * <dl>
 * <dt><b>Title: </b><dd>JBoss14Crypto</dd>
 * <p>
 * <dt><b>Description: </b><dd>Crypto implementation that can be instantiated with a given keystore (presumably 
 * obtained from the SecurityDomain) rather than the properties file expected by Merlin.
 * </dd>
 * <p>
 * </dl>
 * @author <a href="mailto:jasone@greenrivercomputing.com">Jason Essington</a>
 * @version $Revision: 1.3 $
 */
public class JBoss14Crypto extends Merlin implements JBossCrypto
{
   private Logger log = Logger.getLogger(getClass());
   //private KeyStore keystore = null;

   public JBoss14Crypto(KeyStore keystore) throws Exception
   {
      super(null);
      
      //bah, certpath validation requires properties . . .
      this.properties = new Properties();

      if (keystore != null)
      {
         if (log.isDebugEnabled())
            log.debug("Creating new JBoss14Crypto using a " + keystore.getType() + " keystore.");
         setKeyStore(keystore);
         //better save a copy for ourselves as well
         //this.keystore = keystore;
      }
      else
      {
         if (log.isDebugEnabled())
            log.debug("Creating new JBoss14Crypto WITHOUT a keystore.");
      }
   }

   public String getAliasForX500Principal(X500Principal dn) throws Exception
   {
      String alias = null;
      foundcert : for (Enumeration enu = keystore.aliases(); enu.hasMoreElements();)
      {
         String element = (String) enu.nextElement();

         //if (!keystore.isCertificateEntry(element))
         //   continue;

         Certificate[] certs = keystore.getCertificateChain(element);
         if (certs == null)
         {
            Certificate cert = keystore.getCertificate(element);
            if (cert != null)
               certs = new Certificate[]{cert};
         }
         if (certs != null)
         {
            for (int i = 0; i < certs.length; i++)
            {
               if (!(certs[i] instanceof X509Certificate))
                  continue;

               X509Certificate x509cert = (X509Certificate) certs[i];
               if (dn.equals(x509cert.getSubjectX500Principal()))
               {
                  alias = element;
                  break foundcert;
               }
            }
         }
      }
      return alias;
   }
}