All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.cesecore.certificates.certificate.request.PKCS10RequestMessage Maven / Gradle / Ivy

/*************************************************************************
 *                                                                       *
 *  CESeCore: CE Security Core                                           *
 *                                                                       *
 *  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 org.cesecore.certificates.certificate.request;

import java.io.IOException;
import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.bouncycastle.asn1.ASN1Encodable;
import org.bouncycastle.asn1.ASN1Set;
import org.bouncycastle.asn1.ASN1String;
import org.bouncycastle.asn1.DERIA5String;
import org.bouncycastle.asn1.pkcs.Attribute;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.asn1.x500.AttributeTypeAndValue;
import org.bouncycastle.asn1.x500.DirectoryString;
import org.bouncycastle.asn1.x500.RDN;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.asn1.x509.Extension;
import org.bouncycastle.asn1.x509.Extensions;
import org.bouncycastle.cms.CMSSignedGenerator;
import org.bouncycastle.operator.ContentVerifierProvider;
import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.pkcs.PKCS10CertificationRequest;
import org.bouncycastle.pkcs.PKCSException;
import org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequest;
import org.cesecore.util.CeSecoreNameStyle;
import org.cesecore.util.CertTools;

/**
 * Class to handle PKCS10 request messages sent to the CA.
 *
 * @version $Id: PKCS10RequestMessage.java 28214 2018-02-08 10:16:53Z anatom $
 */
public class PKCS10RequestMessage implements RequestMessage {  
    /**
     * Determines if a de-serialized file is compatible with this class.
     *
     * Maintainers must change this value if and only if the new version
     * of this class is not compatible with old versions. See Sun docs
     * for  details. 
     *
     */
    static final long serialVersionUID = 3597275157018205137L;

    private static final Logger log = Logger.getLogger(PKCS10RequestMessage.class);

    /** Raw form of the PKCS10 message */
    protected byte[] p10msg;

    /** manually set password */
    protected String password = null;

    /** manually set username */
    protected String username = null;

    protected Date notAfter = null;
    protected Date notBefore = null;

    /** If the CA certificate should be included in the response or not, default to true = yes */
    protected boolean includeCACert = true;

    /** preferred digest algorithm to use in replies, if applicable */
    private transient String preferredDigestAlg = CMSSignedGenerator.DIGEST_SHA1;

    /** The pkcs10 request message, not serialized. */
    protected transient JcaPKCS10CertificationRequest pkcs10 = null;

    /** Type of error */
    private int error = 0;

    /** Error text */
    private String errorText = null;

    private List additionalCaCertificates = new ArrayList();
    
    private List additionalExtraCertsCertificates = new ArrayList();
    
    /**
     * Constructs a new empty PKCS#10 message handler object.
     */
    public PKCS10RequestMessage() {
    	// No constructor
    }

    /**
     * Constructs a new PKCS#10 message handler object.
     *
     * @param msg The DER encoded PKCS#10 request.
     * @throws IOException
     */
    public PKCS10RequestMessage(byte[] msg) {
    	if (log.isTraceEnabled()) {
    		log.trace(">PKCS10RequestMessage(byte[])");
    	}
        this.p10msg = msg;
        init();
    	if (log.isTraceEnabled()) {
    		log.trace("PKCS10RequestMessage(ExtendedPKCS10CertificationRequest)");
    	}
        p10msg = p10.getEncoded();
        pkcs10 = p10;
    	if (log.isTraceEnabled()) {
    		log.trace(" 0) {
            		ret = ret.substring(0, index);
            	}
            }
        }
        if (log.isDebugEnabled()) {
        	log.debug("UserName='" + ret + "'");
        }
        return ret;
    }

    @Override
    public String getIssuerDN() {
        return null;
    }

    @Override
    public BigInteger getSerialNo() {
    	return null;
    }

    @Override
    public String getCRLIssuerDN() {
        return null;
    }

    @Override
    public BigInteger getCRLSerialNo() {
        return null;
    }

    @Override
    public String getRequestDN() {
    	String ret = null;
    	X500Name name = getRequestX500Name();
    	if (name != null) {
    		String dn = name.toString();
    		// We have to make special handling again for Cisco devices.
    		// they will submit requests like: SN=FFFFFF+unstructuredName=Router
    		// EJBCA does not handle this very well so we will change it to: SN=FFFFFF,unstructuredName=Router
    		dn = dn.replace("+unstructuredName=", ",unstructuredName=");
    		dn = dn.replace(" + unstructuredName=", ",unstructuredName=");
    		dn = dn.replace("+unstructuredAddress=", ",unstructuredAddress=");
    		dn = dn.replace(" + unstructuredAddress=", ",unstructuredAddress=");
    		ret = dn;
    	}
        if (log.isDebugEnabled()) {
        	log.debug("getRequestDN: "+ret);
        }
        return ret;
    }

    @Override
    public X500Name getRequestX500Name() {
        try {
            if (pkcs10 == null) {
                init();
            }
        } catch (NullPointerException e) {
            log.error("PKCS10 not inited: "+e.getMessage());
            return null;
        }
        return X500Name.getInstance(new CeSecoreNameStyle(), pkcs10.getSubject());
    }

    @Override
    public String getRequestAltNames() {
        String ret = null;
        try {
        	Extensions exts = getRequestExtensions();
        	if (exts != null) {
        		Extension ext = exts.getExtension(Extension.subjectAlternativeName);
                if (ext != null) {
                    // Finally read the value
            		ret = CertTools.getAltNameStringFromExtension(ext);
                } else {
                    if (log.isDebugEnabled()) {
                    	log.debug("no subject altName extension");
                    }
                }
        	}
        } catch (IllegalArgumentException e) {
            if (log.isDebugEnabled()) {
            	log.debug("pkcs_9_extensionRequest does not contain Extensions that it should, ignoring invalid encoded extension request.");
            }
        }
        return ret;
    }

    @Override
	public Date getRequestValidityNotBefore() {
        return notBefore;
	}

    @Override
	public Date getRequestValidityNotAfter() {
        return notAfter;
	}

    @Override
	public Extensions getRequestExtensions() {
        try {
            if (pkcs10 == null) {
                init();
            }
        } catch (NullPointerException e) {
            log.error("PKCS10 not inited! "+e.getMessage());
            return null;
        }
        Extensions ret = null;

        // Get attributes
        // The X509 extension is in a a pkcs_9_at_extensionRequest

        // See if we have it embedded in an extension request instead
        Attribute[] attr = pkcs10.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
        if (attr.length != 0) {
            if (log.isDebugEnabled()) {
                log.debug("got request extension");
            }
            ASN1Set values = attr[0].getAttrValues();
            if (values.size() > 0) {
                try {
                    ret = Extensions.getInstance(values.getObjectAt(0));
                } catch (IllegalArgumentException e) {
                    if (log.isDebugEnabled()) {
                        log.debug("pkcs_9_extensionRequest does not contain Extensions that it should, ignoring invalid encoded extension request.");
                    }
                }
            }
        }

        return ret;
	}

    /**
     * Gets the underlying BC PKCS10CertificationRequest object.
     *
     * @return the request object
     */
    public PKCS10CertificationRequest getCertificationRequest() {
        try {
            if (pkcs10 == null) {
                init();
            }
        } catch (NullPointerException e) {
            log.error("PKCS10 not inited! "+e.getMessage());
            return null;
        }

        return pkcs10;
    }

    @Override
    public boolean verify() throws InvalidKeyException, NoSuchAlgorithmException {
        return verify(null);
    }

    public boolean verify(PublicKey pubKey) throws InvalidKeyException, NoSuchAlgorithmException {
    	if (log.isTraceEnabled()) {
    		log.trace(">verify()");
    	}
    	 if (pkcs10 == null) {
             init();
         }

        ContentVerifierProvider verifierProvider;
        try {
            if (pubKey == null) {
                verifierProvider = CertTools.genContentVerifierProvider(pkcs10.getPublicKey());
            } else {
                verifierProvider = CertTools.genContentVerifierProvider(pubKey);
            }
            try {
                return pkcs10.isSignatureValid(verifierProvider);
            } catch (PKCSException e) {
                log.error("Signature could not be processed.", e);
            }
        } catch (OperatorCreationException e) {
            log.error("Content verifier provider could not be created.", e);
        } finally {
            if (log.isTraceEnabled()) {
                log.trace(" getAdditionalCaCertificates() {
        return additionalCaCertificates;
    }

    @Override
    public void setAdditionalCaCertificates(final List certificates) {
        this.additionalCaCertificates = certificates;
    }
    
    @Override
    public List getAdditionalExtraCertsCertificates() {
        return additionalExtraCertsCertificates;
    }

    @Override
    public void setAdditionalExtraCertsCertificates(List additionalExtraCertsCertificates) {
        this.additionalExtraCertsCertificates = additionalExtraCertsCertificates;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy