⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ldappublisher.java

📁 一套JAVA的CA证书签发系统.
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
/************************************************************************* *                                                                       * *  EJBCA: The OpenSource Certificate Authority                          * *                                                                       * *  This software is free software; you can redistribute it and/or       * *  modify it under the terms of the GNU Lesser General Public           * *  License as published by the Free Software Foundation; either         * *  version 2.1 of the License, or any later version.                    * *                                                                       * *  See terms of license at gnu.org.                                     * *                                                                       * *************************************************************************/ package se.anatom.ejbca.ca.publisher;import java.io.ByteArrayInputStream;import java.io.IOException;import java.security.cert.CRLException;import java.security.cert.Certificate;import java.security.cert.CertificateEncodingException;import java.security.cert.CertificateException;import java.security.cert.X509CRL;import java.security.cert.X509Certificate;import java.util.ArrayList;import java.util.Collection;import java.util.Collections;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.StringTokenizer;import org.apache.log4j.Logger;import org.bouncycastle.asn1.ASN1Sequence;import org.bouncycastle.asn1.DERIA5String;import org.bouncycastle.asn1.DERInputStream;import org.bouncycastle.asn1.DEROctetString;import org.bouncycastle.asn1.DERTaggedObject;import se.anatom.ejbca.SecConst;import se.anatom.ejbca.ca.exception.PublisherConnectionException;import se.anatom.ejbca.ca.exception.PublisherException;import se.anatom.ejbca.log.Admin;import se.anatom.ejbca.ra.ExtendedInformation;import se.anatom.ejbca.ra.raadmin.DNFieldExtractor;import se.anatom.ejbca.util.Base64;import se.anatom.ejbca.util.CertTools;import com.novell.ldap.LDAPAttribute;import com.novell.ldap.LDAPAttributeSet;import com.novell.ldap.LDAPConnection;import com.novell.ldap.LDAPEntry;import com.novell.ldap.LDAPException;import com.novell.ldap.LDAPJSSESecureSocketFactory;import com.novell.ldap.LDAPModification;import com.novell.ldap.LDAPModificationSet;/** * LdapPublisher is a class handling a publishing to various v3 LDAP catalouges.   * * @version $Id: LdapPublisher.java,v 1.5 2004/05/19 07:00:31 anatom Exp $ */public class LdapPublisher extends BasePublisher{	 		private static Logger log = Logger.getLogger(LdapPublisher.class);		protected static byte[] fakecrl = null;		public static final float LATEST_VERSION = 1;		public static final int TYPE_LDAPPUBLISHER = 2;			public static final String DEFAULT_USEROBJECTCLASS     = "top;person;organizationalPerson;inetOrgPerson";	public static final String DEFAULT_CAOBJECTCLASS       = "top;applicationProcess;certificationAuthority";	public static final String DEFAULT_CACERTATTRIBUTE     = "cACertificate;binary";	public static final String DEFAULT_USERCERTATTRIBUTE   = "userCertificate;binary";	public static final String DEFAULT_CRLATTRIBUTE        = "certificateRevocationList;binary";	public static final String DEFAULT_ARLATTRIBUTE        = "authorityRevocationList;binary";	public static final String DEFAULT_PORT                = "389";	public static final String DEFAULT_SSLPORT             = "636";			// Default Values        protected static final String HOSTNAME                 = "hostname";    protected static final String USESSL                   = "usessl";    protected static final String PORT                     = "port";    protected static final String BASEDN                   = "baswdn";    protected static final String LOGINDN                  = "logindn";    protected static final String LOGINPASSWORD            = "loginpassword";    protected static final String CREATENONEXISTING        = "createnonexisting";    protected static final String MODIFYEXISTING           = "modifyexisting";        protected static final String USEROBJECTCLASS          = "userobjectclass";    protected static final String CAOBJECTCLASS            = "caobjectclass";    protected static final String USERCERTATTRIBUTE        = "usercertattribute";    protected static final String CACERTATTRIBUTE          = "cacertattribute";    protected static final String CRLATTRIBUTE             = "crlattribute";    protected static final String ARLATTRIBUTE             = "arlattribute";    protected static final String USEFIELDINLDAPDN         = "usefieldsinldapdn";            public LdapPublisher(){    	super();    	data.put(TYPE, new Integer(TYPE_LDAPPUBLISHER));    	        setHostname("");        setUseSSL(true);        setPort(DEFAULT_SSLPORT);        setBaseDN("");        setLoginDN("");        setLoginPassword("");        setCreateNonExisingUsers(true);        setModifyExistingUsers(true);                setUserObjectClass(DEFAULT_USEROBJECTCLASS);        setCAObjectClass(DEFAULT_CAOBJECTCLASS);        setUserCertAttribute(DEFAULT_USERCERTATTRIBUTE);        setCACertAttribute(DEFAULT_CACERTATTRIBUTE);        setCRLAttribute(DEFAULT_CRLATTRIBUTE);        setARLAttribute(DEFAULT_ARLATTRIBUTE);             setUseFieldInLdapDN(new ArrayList());                if(fakecrl == null){          		  try {			X509CRL crl = CertTools.getCRLfromByteArray(fakecrlbytes);			fakecrl = crl.getEncoded();		  } catch (CertificateException e) {}		    catch (CRLException e) {}		    catch (IOException e) {}		}                    }        // Public Methods       	/**	 * @see se.anatom.ejbca.ca.publisher.BasePublisher	 */    	public boolean storeCertificate(Admin admin, Certificate incert, String username, String password, String cafp, int status, int type, ExtendedInformation extendedinformation) throws PublisherException{        log.debug(">storeCertificate(username="+username+")");        int ldapVersion = LDAPConnection.LDAP_V3;        LDAPConnection lc = null;        if(getUseSSL()){          lc = new LDAPConnection(new LDAPJSSESecureSocketFactory());        }else{          lc = new LDAPConnection();                }        String dn = null;        try {            // Extract the users DN from the cert.            dn = constructLDAPDN(CertTools.getSubjectDN((X509Certificate) incert));        } catch (Exception e) {            log.error("Error decoding input certificate: ", e);                        throw new PublisherException("Error decoding input certificate.");                    }        // Extract the users email from the cert.        // First see if we have subjectAltNames extension        String email = null;        byte[] subjAltNameValue = ((X509Certificate) incert).getExtensionValue("2.5.29.17");        // If not, see if we have old styld email-in-DN        if (subjAltNameValue == null) {            email = CertTools.getPartFromDN(dn, "EmailAddress");        } else {            try {                // Get extension value                ByteArrayInputStream bIn = new ByteArrayInputStream(subjAltNameValue);                DEROctetString asn1 = (DEROctetString) new DERInputStream(bIn).readObject();                ByteArrayInputStream bIn1 = new ByteArrayInputStream(asn1.getOctets());                ASN1Sequence san = (ASN1Sequence) new DERInputStream(bIn1).readObject();                for (int i = 0; i < san.size(); i++) {                    DERTaggedObject gn = (DERTaggedObject) san.getObjectAt(i);                    if (gn.getTagNo() == 1) {                        // This is rfc822Name!                        DERIA5String str;                        if (gn.getObject() instanceof DERIA5String) {                            str = (DERIA5String) gn.getObject();                        } else {                            str = new DERIA5String(((DEROctetString) gn.getObject()).getOctets());                        }                        email = str.getString();                    }                }            } catch (IOException e) {                log.error("IOException when getting subjectAltNames extension.");                throw new PublisherException("IOException when getting subjectAltNames extension.");            }        }        // Check if the entry is already present, we will update it with the new certificate.        LDAPEntry oldEntry = null;        try {            // connect to the server            lc.connect(getHostname(), Integer.parseInt(getPort()));            // authenticate to the server            lc.bind(ldapVersion, getLoginDN(), getLoginPassword());            // try to read the old object            oldEntry = lc.read(dn);            // disconnect with the server            lc.disconnect();        } catch (LDAPException e) {            if (e.getLDAPResultCode() == LDAPException.NO_SUCH_OBJECT) {                log.debug("No old entry exist for '" + dn + "'.");                            } else {                log.error("Error binding to and reading from LDAP server: ", e);                throw new PublisherException("Error binding to and reading from LDAP server.");                                            }        }        LDAPEntry newEntry = null;        LDAPModificationSet modSet = null;        LDAPAttributeSet attributeSet = null;        String attribute = null;        String objectclass = null;        if (type == SecConst.CERTTYPE_ENDENTITY) {            log.debug("Publishing end user certificate to " + getHostname());            if (oldEntry != null) {                // TODO: Are we the correct type objectclass?                modSet = getModificationSet(oldEntry, dn, false, true);            } else {                objectclass = getUserObjectClass();            }            attributeSet = getAttributeSet((X509Certificate) incert, getUserObjectClass(), dn, true, true);            if (email != null) {                LDAPAttribute mailAttr = new LDAPAttribute("mail", email);                if (oldEntry != null) {                    modSet.add(LDAPModification.REPLACE, mailAttr);                } else {                    attributeSet.add(mailAttr);                }            }            try {                attribute = getUserCertAttribute();                LDAPAttribute certAttr = new LDAPAttribute(getUserCertAttribute(), incert.getEncoded());                if (oldEntry != null) {                    modSet.add(LDAPModification.REPLACE, certAttr);                                    } else {                    attributeSet.add(certAttr);                }            } catch (CertificateEncodingException e) {                log.error("Error encoding certificate when storing in LDAP: ", e);                throw new PublisherException("Error encoding certificate when storing in LDAP.");                            }        } else if ((type == SecConst.CERTTYPE_SUBCA) || (type == SecConst.CERTTYPE_ROOTCA)) {            log.debug("Publishing CA certificate to " + getHostname());            if (oldEntry != null) {                modSet = getModificationSet(oldEntry, dn, false, false);            } else {                objectclass = getCAObjectClass();            }            attributeSet = getAttributeSet((X509Certificate) incert, getCAObjectClass(), dn, true, false);            try {                attribute = getCACertAttribute();                LDAPAttribute certAttr = new LDAPAttribute(getCACertAttribute(), incert.getEncoded());                if (oldEntry != null) {                    modSet.add(LDAPModification.REPLACE, certAttr);                } else {                    attributeSet.add(certAttr);                    // Also create using the crlattribute, it may be required                    LDAPAttribute crlAttr = new LDAPAttribute(getCRLAttribute(), fakecrl);                    attributeSet.add(crlAttr);                    // Also create using the arlattribute, it may be required                    LDAPAttribute arlAttr = new LDAPAttribute(getARLAttribute(), fakecrl);                    attributeSet.add(arlAttr);                    log.debug("Added (fake) attribute for CRL and ARL.");                }            } catch (CertificateEncodingException e) {                log.error("Error encoding certificate when storing in LDAP: ", e);                throw new PublisherException("Error encoding certificate when storing in LDAP.");                        }        } else {            log.info("Certificate of type '" + type + "' will not be published.");            throw new PublisherException("Certificate of type '" + type + "' will not be published.");                              }        try {                    lc.connect(getHostname(), Integer.parseInt(getPort()));            // authenticate to the server            lc.bind(ldapVersion, getLoginDN(), getLoginPassword());                        // Add or modify the entry            if (oldEntry != null && getModifyExistingUsers()) {                lc.modify(dn, modSet);                log.debug("\nModified object: " + dn + " successfully.");              } else {                if(this.getCreateNonExisingUsers()){                       if (oldEntry == null) {                    newEntry = new LDAPEntry(dn, attributeSet);                  }                  lc.add(newEntry);                  log.debug("\nAdded object: " + dn + " successfully.");                }              }            // disconnect with the server            lc.disconnect();        } catch (LDAPException e) {            log.error("Error storing certificate (" + attribute + ") in LDAP (" + objectclass + "): ", e);              throw new PublisherException("Error storing certificate (" + attribute + ") in LDAP (" + objectclass + ").");                    }        log.debug("<storeCertificate()");        return true;			}		/**	 * @see se.anatom.ejbca.ca.publisher.BasePublisher	 */    	public boolean storeCRL(Admin admin, byte[] incrl, String cafp, int number) throws PublisherException{        int ldapVersion = LDAPConnection.LDAP_V3;        LDAPConnection lc = null;        if(getUseSSL()){          lc = new LDAPConnection(new LDAPJSSESecureSocketFactory());        }else{          lc = new LDAPConnection();                }        X509CRL crl = null;        String dn = null;        try {

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -