Example usage for org.bouncycastle.asn1.x509 X509Extensions oids

List of usage examples for org.bouncycastle.asn1.x509 X509Extensions oids

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x509 X509Extensions oids.

Prototype

public Enumeration oids() 

Source Link

Document

return an Enumeration of the extension field's object ids.

Usage

From source file:chapter6.PKCS10CertCreateExample.java

public static X509Certificate[] buildChain() throws Exception {
    // Create the certification request
    KeyPair pair = Utils.generateRSAKeyPair();

    PKCS10CertificationRequest request = PKCS10ExtensionExample.generateRequest(pair);

    // Create a root certificate
    KeyPair rootPair = Utils.generateRSAKeyPair();
    X509Certificate rootCert = X509V1CreateExample.generateV1Certificate(rootPair);

    // Validate the certification request
    if (request.verify("BC") == false) {
        System.out.println("Request failed to verify!!");
        System.exit(1);// ww  w  .  j a v a  2  s. co  m
    }

    // Create the certificate using the information in the request
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setIssuerDN(rootCert.getSubjectX500Principal());
    certGen.setNotBefore(new Date(System.currentTimeMillis()));
    certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000));
    certGen.setSubjectDN(new X500Principal(request.getCertificationRequestInfo().getSubject().getEncoded()));
    certGen.setPublicKey(request.getPublicKey("BC"));
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(rootCert));
    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            new SubjectKeyIdentifierStructure(request.getPublicKey("BC")));
    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
    certGen.addExtension(X509Extensions.KeyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
    certGen.addExtension(X509Extensions.ExtendedKeyUsage, true,
            new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));

    // Extract the extension request attribute
    ASN1Set attributes = request.getCertificationRequestInfo().getAttributes();

    for (int i = 0; i < attributes.size(); i++) {
        Attribute attr = Attribute.getInstance(attributes.getObjectAt(i));

        // Process extension request
        if (attr.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
            X509Extensions extensions = X509Extensions.getInstance(attr.getAttrValues().getObjectAt(0));

            Enumeration e = extensions.oids();
            while (e.hasMoreElements()) {
                DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement();
                X509Extension ext = extensions.getExtension(oid);

                certGen.addExtension(oid, ext.isCritical(), ext.getValue().getOctets());
            }
        }
    }

    X509Certificate issuedCert = certGen.generateX509Certificate(rootPair.getPrivate());

    return new X509Certificate[] { issuedCert, rootCert };
}

From source file:com.yacme.ext.oxsit.cust_it.comp.security.cert.X509CertDisplayBase_IT.java

License:Open Source License

@Override
public void prepareDisplayStrings(XFrame _xFrame, XComponent _xComp)
        throws IllegalArgumentException, Exception {
    m_xQc = (XOX_X509Certificate) UnoRuntime.queryInterface(XOX_X509Certificate.class, _xComp);
    if (m_xQc == null)
        throw (new IllegalArgumentException(
                "com.yacme.ext.oxsit.security.cert.XOX_X509CertificateDisplay#prepareDisplayStrings wrong argument"));

    ////w  w w . j  a  v a 2s .co  m
    m_aX509 = null; //remove old certificate
    //remove old data from HashMaps
    m_aExtensions.clear();
    m_aExtensionLocalizedNames.clear();
    m_aExtensionDisplayValues.clear();
    m_aCriticalExtensions.clear();
    m_aNotCriticalExtensions.clear();

    ByteArrayInputStream as = new ByteArrayInputStream(m_xQc.getCertificateAttributes().getDEREncoded());
    ASN1InputStream aderin = new ASN1InputStream(as);
    DERObject ado;
    try {
        ado = aderin.readObject();
        m_aX509 = new X509CertificateStructure((ASN1Sequence) ado);
        //initializes the certificate display information
        initSubjectName();
        m_sVersion = String.format("V%d", m_aX509.getVersion());
        m_sSerialNumber = new String("" + m_aX509.getSerialNumber().getValue());
        initIssuerName();
        m_sNotValidBefore = initCertDate(m_aX509.getStartDate().getDate());
        m_sNotValidAfter = initCertDate(m_aX509.getEndDate().getDate());
        m_sSubjectPublicKeyAlgorithm = initPublicKeyAlgorithm();
        m_sSubjectPublicKeyValue = initPublicKeyData();
        m_sSignatureAlgorithm = initSignatureAlgorithm();
        initThumbPrints();
        //now initializes the Extension listing         
        X509Extensions aX509Exts = m_aX509.getTBSCertificate().getExtensions();
        //fill the internal extension HashMaps
        //at the same time we'll get the extension localized name from resources and
        //fill the display data
        MessageConfigurationAccess m_aRegAcc = null;
        m_aRegAcc = new MessageConfigurationAccess(m_xContext, m_xMCF);
        //FIXME: may be we need to adapt this to the context: the following is valid ONLY if this
        //object is instantiated from within a dialog, is not true if instantiated from a not UI method (e.g. from basic for example).
        IDynamicLogger aDlgH = null;
        CertificateExtensionDisplayHelper aHelper = new CertificateExtensionDisplayHelper(m_xContext,
                m_lTheLocale, m_sTimeLocaleString, m_sLocaleDateOfBirth, m_bDisplayOID, m_aLogger);

        for (Enumeration<DERObjectIdentifier> enume = aX509Exts.oids(); enume.hasMoreElements();) {
            DERObjectIdentifier aDERId = enume.nextElement();
            String aTheOID = aDERId.getId();
            X509Extension aext = aX509Exts.getExtension(aDERId);
            m_aExtensions.put(aTheOID, aext);
            //now grab the localized description
            try {
                m_aExtensionLocalizedNames.put(aTheOID, m_aRegAcc.getStringFromRegistry(aTheOID)
                        + ((m_bDisplayOID) ? (" (OID: " + aTheOID.toString() + ")") : ""));
            } catch (com.sun.star.uno.Exception e) {
                m_aLogger.severe("setDEREncoded", e);
                m_aExtensionLocalizedNames.put(aTheOID, aTheOID);
            }
            //and decode this extension
            m_aExtensionDisplayValues.put(aTheOID, aHelper.examineExtension(aext, aDERId, this));

            if (aext.isCritical())
                m_aCriticalExtensions.put(aTheOID, aext);
            else
                m_aNotCriticalExtensions.put(aTheOID, aext);
        }
        m_aRegAcc.dispose();
    } catch (IOException e) {
        m_aLogger.severe("setDEREncoded", e);
    }
}

From source file:ec.rubrica.util.BouncyCastleUtils.java

License:Open Source License

public static boolean certificateHasPolicy(X509Certificate cert, String sOid) {
    try {/*from  w  w  w .  java  2  s  . c  o m*/
        logger.fine("Read cert policies: " + cert.getSerialNumber().toString());

        ByteArrayInputStream bIn = new ByteArrayInputStream(cert.getEncoded());
        ASN1InputStream aIn = new ASN1InputStream(bIn);
        ASN1Sequence seq = (ASN1Sequence) aIn.readObject();
        X509CertificateStructure obj = new X509CertificateStructure(seq);
        TBSCertificateStructure tbsCert = obj.getTBSCertificate();
        if (tbsCert.getVersion() == 3) {
            X509Extensions ext = tbsCert.getExtensions();
            if (ext != null) {
                Enumeration en = ext.oids();
                while (en.hasMoreElements()) {
                    DERObjectIdentifier oid = (DERObjectIdentifier) en.nextElement();
                    X509Extension extVal = ext.getExtension(oid);
                    ASN1OctetString oct = extVal.getValue();
                    ASN1InputStream extIn = new ASN1InputStream(new ByteArrayInputStream(oct.getOctets()));

                    if (oid.equals(X509Extension.certificatePolicies)) {
                        ASN1Sequence cp = (ASN1Sequence) extIn.readObject();
                        for (int i = 0; i != cp.size(); i++) {
                            PolicyInformation pol = PolicyInformation.getInstance(cp.getObjectAt(i));
                            DERObjectIdentifier dOid = pol.getPolicyIdentifier();
                            String soid2 = dOid.getId();

                            logger.fine("Policy: " + soid2);
                            if (soid2.startsWith(sOid))
                                return true;
                        }
                    }
                }
            }

        }
    } catch (Exception ex) {
        logger.severe("Error reading cert policies: " + ex);
    }
    return false;
}

From source file:gov.nih.nci.cagrid.gts.service.ProxyPathValidator.java

License:Apache License

protected void checkProxyConstraints(TBSCertificateStructure proxy, TBSCertificateStructure issuer,
        X509Certificate checkedProxy) throws ProxyPathValidatorException, IOException {

    logger.debug("enter: checkProxyConstraints");

    X509Extensions extensions;
    DERObjectIdentifier oid;/*from  w  ww.  j av a  2 s  .c om*/
    X509Extension ext;

    X509Extension proxyKeyUsage = null;

    extensions = proxy.getExtensions();
    if (extensions != null) {
        Enumeration e = extensions.oids();
        while (e.hasMoreElements()) {
            oid = (DERObjectIdentifier) e.nextElement();
            ext = extensions.getExtension(oid);
            if (oid.equals(X509Extensions.SubjectAlternativeName)
                    || oid.equals(X509Extensions.IssuerAlternativeName)) {
                // No Alt name extensions - 3.2 & 3.5
                throw new ProxyPathValidatorException(ProxyPathValidatorException.PROXY_VIOLATION, checkedProxy,
                        "Proxy certificate cannot contain subject or issuer alternative name extension");
            } else if (oid.equals(X509Extensions.BasicConstraints)) {
                // Basic Constraint must not be true - 3.8
                BasicConstraints basicExt = BouncyCastleUtil.getBasicConstraints(ext);
                if (basicExt.isCA()) {
                    throw new ProxyPathValidatorException(ProxyPathValidatorException.PROXY_VIOLATION,
                            checkedProxy, "Proxy certificate cannot have BasicConstraint CA=true");
                }
            } else if (oid.equals(X509Extensions.KeyUsage)) {
                proxyKeyUsage = ext;

                boolean[] keyUsage = BouncyCastleUtil.getKeyUsage(ext);
                // these must not be asserted
                if (keyUsage[1] || keyUsage[5]) {
                    throw new ProxyPathValidatorException(ProxyPathValidatorException.PROXY_VIOLATION,
                            checkedProxy,
                            "The keyCertSign and nonRepudiation bits must not be asserted in Proxy Certificate");
                }
                boolean[] issuerKeyUsage = getKeyUsage(issuer);
                if (issuerKeyUsage != null) {
                    for (int i = 0; i < 9; i++) {
                        if (i == 1 || i == 5) {
                            continue;
                        }
                        if (!issuerKeyUsage[i] && keyUsage[i]) {
                            throw new ProxyPathValidatorException(ProxyPathValidatorException.PROXY_VIOLATION,
                                    checkedProxy, "Bad KeyUsage in Proxy Certificate");
                        }
                    }
                }
            }
        }
    }

    extensions = issuer.getExtensions();

    if (extensions != null) {
        Enumeration e = extensions.oids();
        while (e.hasMoreElements()) {
            oid = (DERObjectIdentifier) e.nextElement();
            ext = extensions.getExtension(oid);
            if (oid.equals(X509Extensions.KeyUsage)) {
                // If issuer has it then proxy must have it also
                if (proxyKeyUsage == null) {
                    throw new ProxyPathValidatorException(ProxyPathValidatorException.PROXY_VIOLATION,
                            checkedProxy, "KeyUsage extension missing in Proxy Certificate");
                }
                // If issuer has it as critical so does the proxy
                if (ext.isCritical() && !proxyKeyUsage.isCritical()) {
                    throw new ProxyPathValidatorException(ProxyPathValidatorException.PROXY_VIOLATION,
                            checkedProxy, "KeyUsage extension in Proxy Certificate is not critical");
                }
            }
        }
    }

    logger.debug("exit: checkProxyConstraints");
}

From source file:gov.nih.nci.cagrid.gts.service.ProxyPathValidator.java

License:Apache License

protected void checkUnsupportedCriticalExtensions(TBSCertificateStructure crt, int certType,
        X509Certificate checkedProxy) throws ProxyPathValidatorException {

    logger.debug("enter: checkUnsupportedCriticalExtensions");

    X509Extensions extensions = crt.getExtensions();
    if (extensions != null) {
        Enumeration e = extensions.oids();
        while (e.hasMoreElements()) {
            DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement();
            X509Extension ext = extensions.getExtension(oid);
            if (ext.isCritical()) {
                if (oid.equals(X509Extensions.BasicConstraints) || oid.equals(X509Extensions.KeyUsage)
                        || (oid.equals(ProxyCertInfo.OID) && CertUtil.isGsi4Proxy(certType))
                        || (oid.equals(ProxyCertInfo.OLD_OID) && CertUtil.isGsi3Proxy(certType))) {
                } else {
                    throw new ProxyPathValidatorException(ProxyPathValidatorException.UNSUPPORTED_EXTENSION,
                            checkedProxy, "Unsuppored critical exception : " + oid.getId());
                }/*www  .j  ava  2s. c om*/
            }
        }
    }

    logger.debug("exit: checkUnsupportedCriticalExtensions");
}

From source file:io.aos.crypto.spl06.PKCS10CertCreateExample.java

License:Apache License

public static X509Certificate[] buildChain() throws Exception {
    // create the certification request
    KeyPair pair = Utils.generateRSAKeyPair();

    PKCS10CertificationRequest request = PKCS10ExtensionExample.generateRequest(pair);

    // create a root certificate
    KeyPair rootPair = Utils.generateRSAKeyPair();
    X509Certificate rootCert = X509V1CreateExample.generateV1Certificate(rootPair);

    // validate the certification request
    if (!request.verify("BC")) {
        System.out.println("request failed to verify!");
        System.exit(1);/*from  w  w  w  . j  av  a 2  s  .c o m*/
    }

    // create the certificate using the information in the request
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setIssuerDN(rootCert.getSubjectX500Principal());
    certGen.setNotBefore(new Date(System.currentTimeMillis()));
    certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000));
    certGen.setSubjectDN(request.getCertificationRequestInfo().getSubject());
    certGen.setPublicKey(request.getPublicKey("BC"));
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(rootCert));

    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            new SubjectKeyIdentifierStructure(request.getPublicKey("BC")));

    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));

    certGen.addExtension(X509Extensions.KeyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));

    certGen.addExtension(X509Extensions.ExtendedKeyUsage, true,
            new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));

    // extract the extension request attribute
    ASN1Set attributes = request.getCertificationRequestInfo().getAttributes();

    for (int i = 0; i != attributes.size(); i++) {
        Attribute attr = Attribute.getInstance(attributes.getObjectAt(i));

        // process extension request
        if (attr.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
            X509Extensions extensions = X509Extensions.getInstance(attr.getAttrValues().getObjectAt(0));

            Enumeration e = extensions.oids();
            while (e.hasMoreElements()) {
                DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement();
                X509Extension ext = extensions.getExtension(oid);

                certGen.addExtension(oid, ext.isCritical(), ext.getValue().getOctets());
            }
        }
    }

    X509Certificate issuedCert = certGen.generateX509Certificate(rootPair.getPrivate());

    return new X509Certificate[] { issuedCert, rootCert };
}

From source file:org.cesecore.certificates.ocsp.CanLogCache.java

License:Open Source License

private BasicOCSPResp generateBasicOcspResp(OCSPReq ocspRequest, X509Extensions exts,
        List<OCSPResponseItem> responses, String sigAlg, X509Certificate signerCert, PrivateKey signerKey,
        String provider, X509Certificate[] chain, int respIdType)
        throws NotSupportedException, OCSPException, NoSuchProviderException, CryptoTokenOfflineException {
    BasicOCSPResp returnval = null;// w  w  w  . ja va2s.co m
    BasicOCSPRespGenerator basicRes = null;
    basicRes = createOcspResponseGenerator(ocspRequest, signerCert, respIdType);
    if (responses != null) {
        for (OCSPResponseItem item : responses) {
            basicRes.addResponse(item.getCertID(), item.getCertStatus(), item.getThisUpdate(),
                    item.getNextUpdate(), null);
        }
    }
    if (exts != null) {
        @SuppressWarnings("rawtypes")
        Enumeration oids = exts.oids();
        if (oids.hasMoreElements()) {
            basicRes.setResponseExtensions(exts);
        }
    }

    /*
     * The below code breaks the EJB standard by creating its own thread pool and creating a single thread (of the HsmResponseThread 
     * type). The reason for this is that the HSM may deadlock when requesting an OCSP response, which we need to guard against. Since 
     * there is no way of performing this action within the EJB3.0 standard, we are consciously creating threads here. 
     * 
     * Note that this does in no way break the spirit of the EJB standard, which is to not interrupt EJB's transaction handling by 
     * competing with its own thread pool, since these operations have no database impact.
     */

    final ExecutorService service = Executors.newFixedThreadPool(1);
    final Future<BasicOCSPResp> task = service
            .submit(new HsmResponseThread(basicRes, sigAlg, signerKey, chain, provider));

    try {
        returnval = task.get(HsmResponseThread.HSM_TIMEOUT_SECONDS, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        throw new Error("OCSP response retrieval was interrupted while running. This should not happen", e);
    } catch (ExecutionException e) {
        throw new OcspFailureException("Failure encountered while retrieving OCSP response.", e);
    } catch (TimeoutException e) {
        throw new CryptoTokenOfflineException("HSM timed out while trying to get OCSP response", e);
    }

    if (log.isDebugEnabled()) {
        log.debug("Signing OCSP response with OCSP signer cert: " + signerCert.getSubjectDN().getName());
        RespID respId = null;
        if (respIdType == OcspConfiguration.RESPONDERIDTYPE_NAME) {
            respId = new RespID(signerCert.getSubjectX500Principal());
        } else {
            respId = new RespID(signerCert.getPublicKey());
        }
        if (!returnval.getResponderId().equals(respId)) {
            log.error("Response responderId does not match signer certificate responderId!");
        }
        boolean verify = returnval.verify(signerCert.getPublicKey(), "BC");
        if (verify) {
            log.debug("The OCSP response is verifying.");
        } else {
            log.error("The response is NOT verifying!");
        }
    }
    return returnval;
}

From source file:org.ejbca.core.model.ca.caadmin.X509CA.java

License:Open Source License

/**
 * sequence is ignored by X509CA/* w  w  w  .j av  a  2  s  . com*/
 */
public Certificate generateCertificate(UserDataVO subject, X509Name requestX509Name, PublicKey publicKey,
        int keyusage, Date notBefore, Date notAfter, CertificateProfile certProfile, X509Extensions extensions,
        String sequence, PublicKey caPublicKey, PrivateKey caPrivateKey, String provider) throws Exception {

    // We must only allow signing to take place if the CA itself if on line, even if the token is on-line.
    // We have to allow expired as well though, so we can renew expired CAs
    if ((getStatus() != SecConst.CA_ACTIVE) && ((getStatus() != SecConst.CA_EXPIRED))) {
        String msg = intres.getLocalizedMessage("error.caoffline", getName(), getStatus());
        if (log.isDebugEnabled()) {
            log.debug(msg); // This is something we handle so no need to log with higher priority
        }
        throw new CAOfflineException(msg);
    }

    final String sigAlg;
    if (certProfile.getSignatureAlgorithm() == null) {
        sigAlg = getCAInfo().getCATokenInfo().getSignatureAlgorithm();
    } else {
        sigAlg = certProfile.getSignatureAlgorithm();
    }
    final X509Certificate cacert = (X509Certificate) getCACertificate();
    String dn = subject.getCertificateDN();
    // Check if this is a root CA we are creating
    final boolean isRootCA = certProfile.getType() == CertificateProfile.TYPE_ROOTCA;

    // Get certificate validity time notBefore and notAfter
    final CertificateValidity val = new CertificateValidity(subject, certProfile, notBefore, notAfter, cacert,
            isRootCA);

    final X509V3CertificateGenerator certgen = new X509V3CertificateGenerator();
    {
        // Serialnumber is either random bits, where random generator is initialized by the serno generator.
        // Or a custom serial number defined in the end entity object
        final ExtendedInformation ei = subject.getExtendedinformation();
        BigInteger customSN = ei != null ? ei.certificateSerialNumber() : null;
        if (customSN != null) {
            if (!certProfile.getAllowCertSerialNumberOverride()) {
                final String msg = intres.getLocalizedMessage(
                        "signsession.certprof_not_allowing_cert_sn_override_using_normal",
                        customSN.toString(16));
                log.info(msg);
                customSN = null;
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Using custom serial number: " + customSN.toString(16));
                }
            }
        }
        final BigInteger serno = customSN != null ? customSN : SernoGenerator.instance().getSerno();
        certgen.setSerialNumber(serno);
    }
    certgen.setNotBefore(val.getNotBefore());
    certgen.setNotAfter(val.getNotAfter());
    certgen.setSignatureAlgorithm(sigAlg);

    // Make DNs
    if (certProfile.getUseSubjectDNSubSet()) {
        dn = certProfile.createSubjectDNSubSet(dn);
    }

    if (certProfile.getUseCNPostfix()) {
        dn = CertTools.insertCNPostfix(dn, certProfile.getCNPostfix());
    }

    X509NameEntryConverter converter = null;
    if (getUsePrintableStringSubjectDN()) {
        converter = new PrintableStringEntryConverter();
    } else {
        converter = new X509DefaultEntryConverter();
    }
    // Will we use LDAP DN order (CN first) or X500 DN order (CN last) for the subject DN
    boolean ldapdnorder = true;
    if ((getUseLdapDNOrder() == false) || (certProfile.getUseLdapDnOrder() == false)) {
        ldapdnorder = false;
    }
    X509Name subjectDNName = CertTools.stringToBcX509Name(dn, converter, ldapdnorder);
    if (certProfile.getAllowDNOverride() && (requestX509Name != null)) {
        subjectDNName = requestX509Name;
        if (log.isDebugEnabled()) {
            log.debug("Using X509Name from request instead of user's registered.");
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("Using subjectDN: " + subjectDNName.toString());
    }
    certgen.setSubjectDN(subjectDNName);
    // We must take the issuer DN directly from the CA-certificate otherwise we risk re-ordering the DN
    // which many applications do not like.
    if (isRootCA) {
        // This will be an initial root CA, since no CA-certificate exists
        // Or it is a root CA, since the cert is self signed. If it is a root CA we want to use the same encoding for subject and issuer,
        // it might have changed over the years.
        if (log.isDebugEnabled()) {
            log.debug("Using subject DN also as issuer DN, because it is a root CA");
        }
        certgen.setIssuerDN(subjectDNName);
    } else {
        javax.security.auth.x500.X500Principal issuerPrincipal = cacert.getSubjectX500Principal();
        if (log.isDebugEnabled()) {
            log.debug("Using issuer DN directly from the CA certificate: " + issuerPrincipal.getName());
        }
        certgen.setIssuerDN(issuerPrincipal);
    }
    certgen.setPublicKey(publicKey);

    //
    // X509 Certificate Extensions
    //

    // Extensions we will add to the certificate, later when we have filled the structure with 
    // everything we want.
    X509ExtensionsGenerator extgen = new X509ExtensionsGenerator();

    // First we check if there is general extension override, and add all extensions from 
    // the request in that case
    if (certProfile.getAllowExtensionOverride() && extensions != null) {
        Enumeration en = extensions.oids();
        while (en != null && en.hasMoreElements()) {
            DERObjectIdentifier oid = (DERObjectIdentifier) en.nextElement();
            X509Extension ext = extensions.getExtension(oid);
            if (log.isDebugEnabled()) {
                log.debug("Overriding extension with oid: " + oid);
            }
            extgen.addExtension(oid, ext.isCritical(), ext.getValue().getOctets());
        }
    }

    // Second we see if there is Key usage override
    X509Extensions overridenexts = extgen.generate();
    if (certProfile.getAllowKeyUsageOverride() && (keyusage >= 0)) {
        if (log.isDebugEnabled()) {
            log.debug("AllowKeyUsageOverride=true. Using KeyUsage from parameter: " + keyusage);
        }
        if ((certProfile.getUseKeyUsage() == true) && (keyusage >= 0)) {
            X509KeyUsage ku = new X509KeyUsage(keyusage);
            // We don't want to try to add custom extensions with the same oid if we have already added them 
            // from the request, if AllowExtensionOverride is enabled.
            // Two extensions with the same oid is not allowed in the standard.
            if (overridenexts.getExtension(X509Extensions.KeyUsage) == null) {
                extgen.addExtension(X509Extensions.KeyUsage, certProfile.getKeyUsageCritical(), ku);
            } else {
                if (log.isDebugEnabled()) {
                    log.debug(
                            "KeyUsage was already overridden by an extension, not using KeyUsage from parameter.");
                }
            }
        }
    }

    // Third, check for standard Certificate Extensions that should be added.
    // Standard certificate extensions are defined in CertificateProfile and CertificateExtensionFactory
    // and implemented in package org.ejbca.core.model.certextensions.standard
    CertificateExtensionFactory fact = CertificateExtensionFactory.getInstance();
    List<String> usedStdCertExt = certProfile.getUsedStandardCertificateExtensions();
    Iterator<String> certStdExtIter = usedStdCertExt.iterator();
    overridenexts = extgen.generate();
    while (certStdExtIter.hasNext()) {
        String oid = certStdExtIter.next();
        // We don't want to try to add standard extensions with the same oid if we have already added them 
        // from the request, if AllowExtensionOverride is enabled.
        // Two extensions with the same oid is not allowed in the standard.
        if (overridenexts.getExtension(new DERObjectIdentifier(oid)) == null) {
            CertificateExtension certExt = fact.getStandardCertificateExtension(oid, certProfile);
            if (certExt != null) {
                byte[] value = certExt.getValueEncoded(subject, this, certProfile, publicKey, caPublicKey);
                if (value != null) {
                    extgen.addExtension(new DERObjectIdentifier(certExt.getOID()), certExt.isCriticalFlag(),
                            value);
                }
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Extension with oid " + oid
                        + " has been overridden, standard extension will not be added.");
            }
        }
    }

    // Fourth, check for custom Certificate Extensions that should be added.
    // Custom certificate extensions is defined in certextensions.properties
    fact = CertificateExtensionFactory.getInstance();
    List<Integer> usedCertExt = certProfile.getUsedCertificateExtensions();
    Iterator<Integer> certExtIter = usedCertExt.iterator();
    while (certExtIter.hasNext()) {
        Integer id = certExtIter.next();
        CertificateExtension certExt = fact.getCertificateExtensions(id);
        if (certExt != null) {
            // We don't want to try to add custom extensions with the same oid if we have already added them 
            // from the request, if AllowExtensionOverride is enabled.
            // Two extensions with the same oid is not allowed in the standard.
            if (overridenexts.getExtension(new DERObjectIdentifier(certExt.getOID())) == null) {
                byte[] value = certExt.getValueEncoded(subject, this, certProfile, publicKey, caPublicKey);
                if (value != null) {
                    extgen.addExtension(new DERObjectIdentifier(certExt.getOID()), certExt.isCriticalFlag(),
                            value);
                }
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Extension with oid " + certExt.getOID()
                            + " has been overridden, custom extension will not be added.");
                }
            }
        }
    }

    // Finally add extensions to certificate generator
    X509Extensions exts = extgen.generate();
    Enumeration en = exts.oids();
    while (en.hasMoreElements()) {
        DERObjectIdentifier oid = (DERObjectIdentifier) en.nextElement();
        X509Extension ext = exts.getExtension(oid);
        certgen.addExtension(oid, ext.isCritical(), ext.getValue().getOctets());
    }

    //
    // End of extensions
    //

    X509Certificate cert;
    if (log.isTraceEnabled()) {
        log.trace(">certgen.generate");
    }
    cert = certgen.generate(caPrivateKey, provider);
    if (log.isTraceEnabled()) {
        log.trace("<certgen.generate");
    }

    // Verify using the CA certificate before returning
    // If we can not verify the issued certificate using the CA certificate we don't want to issue this cert
    // because something is wrong...
    PublicKey verifyKey;
    // We must use the configured public key if this is a rootCA, because then we can renew our own certificate, after changing
    // the keys. In this case the _new_ key will not match the current CA certificate.
    if ((cacert != null) && (!isRootCA)) {
        verifyKey = cacert.getPublicKey();
    } else {
        verifyKey = caPublicKey;
    }
    cert.verify(verifyKey);

    // If we have a CA-certificate, verify that we have all path verification stuff correct
    if (cacert != null) {
        byte[] aki = CertTools.getAuthorityKeyId(cert);
        byte[] ski = CertTools.getSubjectKeyId(isRootCA ? cert : cacert);
        if ((aki != null) && (ski != null)) {
            boolean eq = Arrays.equals(aki, ski);
            if (!eq) {
                String akistr = new String(Hex.encode(aki));
                String skistr = new String(Hex.encode(ski));
                log.error(intres.getLocalizedMessage("signsession.errorpathverifykeyid", akistr, skistr));
            }
        }
        Principal issuerDN = cert.getIssuerX500Principal();
        Principal subjectDN = cacert.getSubjectX500Principal();
        if ((issuerDN != null) && (subjectDN != null)) {
            boolean eq = issuerDN.equals(subjectDN);
            if (!eq) {
                log.error(intres.getLocalizedMessage("signsession.errorpathverifydn", issuerDN.getName(),
                        subjectDN.getName()));
            }
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("X509CA: generated certificate, CA " + this.getCAId() + " for DN: "
                + subject.getCertificateDN());
    }
    return cert;
}

From source file:org.ejbca.core.protocol.ocsp.OCSPUtil.java

License:Open Source License

public static BasicOCSPResp generateBasicOCSPResp(OCSPCAServiceRequest serviceReq, String sigAlg,
        X509Certificate signerCert, PrivateKey signerKey, String provider, X509Certificate[] chain,
        int respIdType)
        throws NotSupportedException, OCSPException, NoSuchProviderException, IllegalArgumentException {
    BasicOCSPResp returnval = null;/*from  w  w w .ja v  a  2s .c o m*/
    BasicOCSPRespGenerator basicRes = null;
    basicRes = OCSPUtil.createOCSPResponse(serviceReq.getOCSPrequest(), signerCert, respIdType);
    ArrayList responses = serviceReq.getResponseList();
    if (responses != null) {
        Iterator iter = responses.iterator();
        while (iter.hasNext()) {
            OCSPResponseItem item = (OCSPResponseItem) iter.next();
            basicRes.addResponse(item.getCertID(), item.getCertStatus(), item.getThisUpdate(),
                    item.getNextUpdate(), null);
        }
    }
    X509Extensions exts = serviceReq.getExtensions();
    if (exts != null) {
        Enumeration oids = exts.oids();
        if (oids.hasMoreElements()) {
            basicRes.setResponseExtensions(exts);
        }
    }

    returnval = basicRes.generate(sigAlg, signerKey, chain, new Date(), provider);
    if (m_log.isDebugEnabled()) {
        m_log.debug("Signing OCSP response with OCSP signer cert: " + signerCert.getSubjectDN().getName());
        RespID respId = null;
        if (respIdType == OcspConfiguration.RESPONDERIDTYPE_NAME) {
            respId = new RespID(signerCert.getSubjectX500Principal());
        } else {
            respId = new RespID(signerCert.getPublicKey());
        }
        if (!returnval.getResponderId().equals(respId)) {
            m_log.error("Response responderId does not match signer certificate responderId!");
        }
        boolean verify = returnval.verify(signerCert.getPublicKey(), "BC");
        if (verify) {
            m_log.debug("The OCSP response is verifying.");
        } else {
            m_log.error("The response is NOT verifying!");
        }
    }
    return returnval;
}

From source file:org.glite.slcs.pki.CertificateRequest.java

License:eu-egee.org license

/**
 * Returns a List of certificate extensions contained in the certificate
 * request.//from w ww  .ja  v a 2 s. c om
 * 
 * @return The List of CertificateExtension
 */
public List getCertificateExtensions() {
    List certificateExtensions = new ArrayList();
    X509Extensions x509Extensions = pkcs10_.getX509Extensions();
    if (x509Extensions != null) {
        Enumeration oids = x509Extensions.oids();
        while (oids.hasMoreElements()) {
            DERObjectIdentifier oid = (DERObjectIdentifier) oids.nextElement();
            X509Extension x509Extension = x509Extensions.getExtension(oid);
            boolean critical = x509Extension.isCritical();
            CertificateExtension extension = new CertificateExtension(oid, x509Extension, critical);
            certificateExtensions.add(extension);
        }
    }
    return certificateExtensions;
}