Example usage for org.bouncycastle.asn1.x509 Extension getParsedValue

List of usage examples for org.bouncycastle.asn1.x509 Extension getParsedValue

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x509 Extension getParsedValue.

Prototype

public ASN1Encodable getParsedValue() 

Source Link

Usage

From source file:com.vmware.admiral.common.util.CertificateUtil.java

License:Open Source License

private static List<ExtensionHolder> getServerExtensions(X509Certificate issuerCertificate)
        throws CertificateEncodingException, NoSuchAlgorithmException, IOException {
    List<ExtensionHolder> extensions = new ArrayList<>();

    // SSO forces us to allow data encipherment
    extensions.add(new ExtensionHolder(Extension.keyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment)));

    extensions.add(new ExtensionHolder(Extension.extendedKeyUsage, true,
            new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth)));

    Extension authorityKeyExtension = new Extension(Extension.authorityKeyIdentifier, false,
            new DEROctetString(new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(issuerCertificate)));
    extensions.add(new ExtensionHolder(authorityKeyExtension.getExtnId(), authorityKeyExtension.isCritical(),
            authorityKeyExtension.getParsedValue()));

    return extensions;
}

From source file:eu.europa.esig.dss.x509.ocsp.OCSPToken.java

License:Open Source License

private void extractArchiveCutOff() {
    Extension extension = basicOCSPResp.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_archive_cutoff);
    if (extension != null) {
        ASN1GeneralizedTime archiveCutOffAsn1 = (ASN1GeneralizedTime) extension.getParsedValue();
        try {/*from   w  w  w.j  a va  2  s  . co  m*/
            archiveCutOff = archiveCutOffAsn1.getDate();
        } catch (ParseException e) {
            logger.warn("Unable to extract id_pkix_ocsp_archive_cutoff : " + e.getMessage());
        }
    }
}

From source file:org.apache.jmeter.assertions.SMIMEAssertion.java

License:Apache License

/**
 * Extract email addresses from a certificate
 * //  ww w.  ja  va 2 s. c  o m
 * @param cert the X509 certificate holder
 * @return a List of all email addresses found
 * @throws CertificateException
 */
private static List<String> getEmailFromCert(X509CertificateHolder cert) throws CertificateException {
    List<String> res = new ArrayList<>();

    X500Name subject = cert.getSubject();
    for (RDN emails : subject.getRDNs(BCStyle.EmailAddress)) {
        for (AttributeTypeAndValue emailAttr : emails.getTypesAndValues()) {
            log.debug("Add email from RDN: " + IETFUtils.valueToString(emailAttr.getValue()));
            res.add(IETFUtils.valueToString(emailAttr.getValue()));
        }
    }

    Extension subjectAlternativeNames = cert.getExtension(Extension.subjectAlternativeName);
    if (subjectAlternativeNames != null) {
        for (GeneralName name : GeneralNames.getInstance(subjectAlternativeNames.getParsedValue()).getNames()) {
            if (name.getTagNo() == GeneralName.rfc822Name) {
                String email = IETFUtils.valueToString(name.getName());
                log.debug("Add email from subjectAlternativeName: " + email);
                res.add(email);
            }
        }
    }

    return res;
}

From source file:org.cesecore.certificates.ca.X509CA.java

License:Open Source License

/**
 * Sequence is ignored by X509CA. The ctParams argument will NOT be kept after the function call returns,
 * and is allowed to contain references to session beans.
 * /*  w w w  . jav a  2  s. c o  m*/
 * @throws CAOfflineException if the CA wasn't active
 * @throws InvalidAlgorithmException if the signing algorithm in the certificate profile (or the CA Token if not found) was invalid.  
 * @throws IllegalValidityException if validity was invalid
 * @throws IllegalNameException if the name specified in the certificate request was invalid
 * @throws CertificateExtensionException if any of the certificate extensions were invalid
 * @throws OperatorCreationException if CA's private key contained an unknown algorithm or provider
 * @throws CertificateCreateException if an error occurred when trying to create a certificate. 
 * @throws SignatureException if the CA's certificate's and request's certificate's and signature algorithms differ
 */
private Certificate generateCertificate(final EndEntityInformation subject, final RequestMessage request,
        final PublicKey publicKey, final int keyusage, final Date notBefore, final Date notAfter,
        final CertificateProfile certProfile, final Extensions extensions, final String sequence,
        final PublicKey caPublicKey, final PrivateKey caPrivateKey, final String provider,
        CertificateGenerationParams certGenParams) throws CAOfflineException, InvalidAlgorithmException,
        IllegalValidityException, IllegalNameException, CertificateExtensionException,
        OperatorCreationException, CertificateCreateException, SignatureException {

    // We must only allow signing to take place if the CA itself is 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() != CAConstants.CA_ACTIVE) && ((getStatus() != CAConstants.CA_EXPIRED))) {
        final 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 = getCAToken().getSignatureAlgorithm();
    } else {
        sigAlg = certProfile.getSignatureAlgorithm();
    }
    // Check that the signature algorithm is one of the allowed ones
    if (!ArrayUtils.contains(AlgorithmConstants.AVAILABLE_SIGALGS, sigAlg)) {
        final String msg = intres.getLocalizedMessage("createcert.invalidsignaturealg", sigAlg);
        throw new InvalidAlgorithmException(msg);
    }
    // Check if this is a root CA we are creating
    final boolean isRootCA = certProfile.getType() == CertificateConstants.CERTTYPE_ROOTCA;

    final X509Certificate cacert = (X509Certificate) getCACertificate();
    // Check CA certificate PrivateKeyUsagePeriod if it exists (throws CAOfflineException if it exists and is not within this time)
    CertificateValidity.checkPrivateKeyUsagePeriod(cacert);
    // Get certificate validity time notBefore and notAfter
    final CertificateValidity val = new CertificateValidity(subject, certProfile, notBefore, notAfter, cacert,
            isRootCA);

    final BigInteger serno;
    {
        // 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();
        if (certProfile.getAllowCertSerialNumberOverride()) {
            if (ei != null && ei.certificateSerialNumber() != null) {
                serno = ei.certificateSerialNumber();
            } else {
                serno = SernoGeneratorRandom.instance().getSerno();
            }
        } else {
            serno = SernoGeneratorRandom.instance().getSerno();
            if ((ei != null) && (ei.certificateSerialNumber() != null)) {
                final String msg = intres.getLocalizedMessage(
                        "createcert.certprof_not_allowing_cert_sn_override_using_normal",
                        ei.certificateSerialNumber().toString(16));
                log.info(msg);
            }
        }
    }

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

    final X500NameStyle nameStyle;
    if (getUsePrintableStringSubjectDN()) {
        nameStyle = PrintableStringNameStyle.INSTANCE;
    } else {
        nameStyle = CeSecoreNameStyle.INSTANCE;
    }

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

    // Will we use LDAP DN order (CN first) or X500 DN order (CN last) for the subject DN
    final boolean ldapdnorder;
    if ((getUseLdapDNOrder() == false) || (certProfile.getUseLdapDnOrder() == false)) {
        ldapdnorder = false;
    } else {
        ldapdnorder = true;
    }
    final X500Name subjectDNName;
    if (certProfile.getAllowDNOverride() && (request != null) && (request.getRequestX500Name() != null)) {
        subjectDNName = request.getRequestX500Name();
        if (log.isDebugEnabled()) {
            log.debug("Using X509Name from request instead of user's registered.");
        }
    } else {
        final ExtendedInformation ei = subject.getExtendedinformation();
        if (certProfile.getAllowDNOverrideByEndEntityInformation() && ei != null
                && ei.getRawSubjectDn() != null) {
            final String stripped = StringTools.strip(ei.getRawSubjectDn());
            final String escapedPluses = CertTools.handleUnescapedPlus(stripped);
            final String emptiesRemoved = DNFieldsUtil.removeAllEmpties(escapedPluses);
            final X500Name subjectDNNameFromEei = CertTools.stringToUnorderedX500Name(emptiesRemoved,
                    CeSecoreNameStyle.INSTANCE);
            if (subjectDNNameFromEei.toString().length() > 0) {
                subjectDNName = subjectDNNameFromEei;
                if (log.isDebugEnabled()) {
                    log.debug(
                            "Using X500Name from end entity information instead of user's registered subject DN fields.");
                    log.debug("ExtendedInformation.getRawSubjectDn(): " + ei.getRawSubjectDn() + " will use: "
                            + CeSecoreNameStyle.INSTANCE.toString(subjectDNName));
                }
            } else {
                subjectDNName = CertTools.stringToBcX500Name(dn, nameStyle, ldapdnorder);
            }
        } else {
            subjectDNName = CertTools.stringToBcX500Name(dn, nameStyle, ldapdnorder);
        }
    }
    // Make sure the DN does not contain dangerous characters
    if (StringTools.hasStripChars(subjectDNName.toString())) {
        if (log.isTraceEnabled()) {
            log.trace("DN with illegal name: " + subjectDNName);
        }
        final String msg = intres.getLocalizedMessage("createcert.illegalname");
        throw new IllegalNameException(msg);
    }
    if (log.isDebugEnabled()) {
        log.debug("Using subjectDN: " + subjectDNName.toString());
    }

    // We must take the issuer DN directly from the CA-certificate otherwise we risk re-ordering the DN
    // which many applications do not like.
    X500Name issuerDNName;
    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");
        }
        issuerDNName = subjectDNName;
    } else {
        issuerDNName = X500Name.getInstance(cacert.getSubjectX500Principal().getEncoded());
        if (log.isDebugEnabled()) {
            log.debug("Using issuer DN directly from the CA certificate: " + issuerDNName.toString());
        }
    }

    SubjectPublicKeyInfo pkinfo;
    try {
        pkinfo = new SubjectPublicKeyInfo((ASN1Sequence) ASN1Primitive.fromByteArray(publicKey.getEncoded()));
    } catch (IOException e) {
        throw new IllegalStateException("Caught unexpected IOException.", e);
    }
    final X509v3CertificateBuilder certbuilder = new X509v3CertificateBuilder(issuerDNName, serno,
            val.getNotBefore(), val.getNotAfter(), subjectDNName, pkinfo);

    // Only created and used if Certificate Transparency is enabled
    final X509v3CertificateBuilder precertbuilder = certProfile.isUseCertificateTransparencyInCerts()
            ? new X509v3CertificateBuilder(issuerDNName, serno, val.getNotBefore(), val.getNotAfter(),
                    subjectDNName, pkinfo)
            : null;

    // Check that the certificate fulfills name constraints
    if (cacert instanceof X509Certificate) {
        GeneralNames altNameGNs = null;
        String altName = subject.getSubjectAltName();
        if (certProfile.getUseSubjectAltNameSubSet()) {
            altName = certProfile.createSubjectAltNameSubSet(altName);
        }
        if (altName != null && altName.length() > 0) {
            altNameGNs = CertTools.getGeneralNamesFromAltName(altName);
        }
        CertTools.checkNameConstraints((X509Certificate) cacert, subjectDNName, altNameGNs);
    }

    // If the subject has Name Constraints, then name constraints must be enabled in the certificate profile!
    if (subject.getExtendedinformation() != null) {
        final ExtendedInformation ei = subject.getExtendedinformation();
        final List<String> permittedNC = ei.getNameConstraintsPermitted();
        final List<String> excludedNC = ei.getNameConstraintsExcluded();
        if ((permittedNC != null && !permittedNC.isEmpty()) || (excludedNC != null && !excludedNC.isEmpty())) {
            if (!certProfile.getUseNameConstraints()) {
                throw new CertificateCreateException(
                        "Tried to issue a certificate with Name Constraints without having enabled NC in the certificate profile.");
            }
        }
    }

    //
    // X509 Certificate Extensions
    //

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

    // First we check if there is general extension override, and add all extensions from
    // the request in that case
    if (certProfile.getAllowExtensionOverride() && extensions != null) {
        ASN1ObjectIdentifier[] oids = extensions.getExtensionOIDs();
        for (ASN1ObjectIdentifier oid : oids) {
            final Extension ext = extensions.getExtension(oid);
            if (log.isDebugEnabled()) {
                log.debug("Overriding extension with oid: " + oid);
            }
            try {
                extgen.addExtension(oid, ext.isCritical(), ext.getParsedValue());
            } catch (IOException e) {
                throw new IllegalStateException("Caught unexpected IOException.", e);
            }
        }
    }

    // Second we see if there is Key usage override
    Extensions 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)) {
            final KeyUsage ku = new KeyUsage(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(Extension.keyUsage) == null) {
                try {
                    extgen.addExtension(Extension.keyUsage, certProfile.getKeyUsageCritical(), ku);
                } catch (IOException e) {
                    throw new IllegalStateException("Caught unexpected IOException.", e);
                }
            } 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
    final CertificateExtensionFactory fact = CertificateExtensionFactory.getInstance();
    final List<String> usedStdCertExt = certProfile.getUsedStandardCertificateExtensions();
    final Iterator<String> certStdExtIter = usedStdCertExt.iterator();
    overridenexts = extgen.generate();
    while (certStdExtIter.hasNext()) {
        final 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 ASN1ObjectIdentifier(oid)) == null) {
            final CertificateExtension certExt = fact.getStandardCertificateExtension(oid, certProfile);
            if (certExt != null) {
                final byte[] value = certExt.getValueEncoded(subject, this, certProfile, publicKey, caPublicKey,
                        val);
                if (value != null) {
                    extgen.addExtension(new ASN1ObjectIdentifier(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
    final List<Integer> usedCertExt = certProfile.getUsedCertificateExtensions();
    final Iterator<Integer> certExtIter = usedCertExt.iterator();
    while (certExtIter.hasNext()) {
        final Integer id = certExtIter.next();
        final 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 ASN1ObjectIdentifier(certExt.getOID())) == null) {
                final byte[] value = certExt.getValueEncoded(subject, this, certProfile, publicKey, caPublicKey,
                        val);
                if (value != null) {
                    extgen.addExtension(new ASN1ObjectIdentifier(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
    final Extensions exts = extgen.generate();
    ASN1ObjectIdentifier[] oids = exts.getExtensionOIDs();
    try {
        for (ASN1ObjectIdentifier oid : oids) {
            final Extension extension = exts.getExtension(oid);
            if (oid.equals(Extension.subjectAlternativeName)) { // subjectAlternativeName extension value needs special handling
                ExtensionsGenerator sanExtGen = getSubjectAltNameExtensionForCert(extension,
                        precertbuilder != null);
                Extensions sanExts = sanExtGen.generate();
                Extension eext = sanExts.getExtension(oid);
                certbuilder.addExtension(oid, eext.isCritical(), eext.getParsedValue()); // adding subjetAlternativeName extension to certbuilder
                if (precertbuilder != null) { // if a pre-certificate is to be published to a CTLog
                    eext = getSubjectAltNameExtensionForCTCert(extension).generate().getExtension(oid);
                    precertbuilder.addExtension(oid, eext.isCritical(), eext.getParsedValue()); // adding subjectAlternativeName extension to precertbuilder

                    eext = sanExts.getExtension(new ASN1ObjectIdentifier("1.3.6.1.4.1.11129.2.4.6"));
                    if (eext != null) {
                        certbuilder.addExtension(eext.getExtnId(), eext.isCritical(), eext.getParsedValue()); // adding nrOfRedactedLabels extension to certbuilder
                    }
                }
            } else { // if not a subjectAlternativeName extension, just add it to both certbuilder and precertbuilder 
                final boolean isCritical = extension.isCritical();
                // We must get the raw octets here in order to be able to create invalid extensions that is not constructed from proper ASN.1
                final byte[] value = extension.getExtnValue().getOctets();
                certbuilder.addExtension(extension.getExtnId(), isCritical, value);
                if (precertbuilder != null) {
                    precertbuilder.addExtension(extension.getExtnId(), isCritical, value);
                }
            }
        }

        // Add Certificate Transparency extension. It needs to access the certbuilder and
        // the CA key so it has to be processed here inside X509CA.
        if (ct != null && certProfile.isUseCertificateTransparencyInCerts()
                && certGenParams.getConfiguredCTLogs() != null
                && certGenParams.getCTAuditLogCallback() != null) {

            // Create pre-certificate
            // A critical extension is added to prevent this cert from being used
            ct.addPreCertPoison(precertbuilder);

            // Sign pre-certificate
            /*
             *  TODO: Should be able to use a special CT signing certificate.
             *  It should have CA=true and ExtKeyUsage=PRECERTIFICATE_SIGNING_OID,
             *  and should not have any other key usages.
             */
            final ContentSigner signer = new BufferingContentSigner(
                    new JcaContentSignerBuilder(sigAlg).setProvider(provider).build(caPrivateKey), 20480);
            final X509CertificateHolder certHolder = precertbuilder.build(signer);
            final X509Certificate cert = (X509Certificate) CertTools
                    .getCertfromByteArray(certHolder.getEncoded());

            // Get certificate chain
            final List<Certificate> chain = new ArrayList<Certificate>();
            chain.add(cert);
            chain.addAll(getCertificateChain());

            // Submit to logs and get signed timestamps
            byte[] sctlist = null;
            try {
                sctlist = ct.fetchSCTList(chain, certProfile, certGenParams.getConfiguredCTLogs());
            } finally {
                // Notify that pre-cert has been successfully or unsuccessfully submitted so it can be audit logged.
                certGenParams.getCTAuditLogCallback().logPreCertSubmission(this, subject, cert,
                        sctlist != null);
            }
            if (sctlist != null) { // can be null if the CTLog has been deleted from the configuration
                ASN1ObjectIdentifier sctOid = new ASN1ObjectIdentifier(CertificateTransparency.SCTLIST_OID);
                certbuilder.addExtension(sctOid, false, new DEROctetString(sctlist));
            }
        } else {
            if (log.isDebugEnabled()) {
                String cause = "";
                if (ct == null) {
                    cause += "CT is not available in this version of EJBCA.";
                } else {
                    if (!certProfile.isUseCertificateTransparencyInCerts()) {
                        cause += "CT is not enabled in the certificate profile. ";
                    }
                    if (certGenParams == null) {
                        cause += "Certificate generation parameters was null.";
                    } else if (certGenParams.getCTAuditLogCallback() == null) {
                        cause += "No CT audit logging callback was passed to X509CA.";
                    } else if (certGenParams.getConfiguredCTLogs() == null) {
                        cause += "There are no CT logs configured in System Configuration.";
                    }
                }
                log.debug("Not logging to CT. " + cause);
            }
        }
    } catch (CertificateException e) {
        throw new CertificateCreateException(
                "Could not process CA's private key when parsing Certificate Transparency extension.", e);
    } catch (IOException e) {
        throw new CertificateCreateException(
                "IOException was caught when parsing Certificate Transparency extension.", e);
    } catch (CTLogException e) {
        throw new CertificateCreateException(
                "An exception occurred because too many CT servers were down to satisfy the certificate profile.",
                e);
    }

    //
    // End of extensions
    //

    if (log.isTraceEnabled()) {
        log.trace(">certgen.generate");
    }
    final ContentSigner signer = new BufferingContentSigner(
            new JcaContentSignerBuilder(sigAlg).setProvider(provider).build(caPrivateKey), 20480);
    final X509CertificateHolder certHolder = certbuilder.build(signer);
    X509Certificate cert;
    try {
        cert = (X509Certificate) CertTools.getCertfromByteArray(certHolder.getEncoded());
    } catch (IOException e) {
        throw new IllegalStateException("Unexpected IOException caught when parsing certificate holder.", e);
    } catch (CertificateException e) {
        throw new CertificateCreateException("Could not create certificate from CA's private key,", e);
    }
    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...
    final 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;
    }
    try {
        cert.verify(verifyKey);
    } catch (InvalidKeyException e) {
        throw new CertificateCreateException("CA's public key was invalid,", e);
    } catch (NoSuchAlgorithmException e) {
        throw new CertificateCreateException(e);
    } catch (NoSuchProviderException e) {
        throw new IllegalStateException("Provider was unknown", e);
    } catch (CertificateException e) {
        throw new CertificateCreateException(e);
    }

    // If we have a CA-certificate, verify that we have all path verification stuff correct
    if (cacert != null) {
        final byte[] aki = CertTools.getAuthorityKeyId(cert);
        final byte[] ski = CertTools.getSubjectKeyId(isRootCA ? cert : cacert);
        if ((aki != null) && (ski != null)) {
            final boolean eq = Arrays.equals(aki, ski);
            if (!eq) {
                final String akistr = new String(Hex.encode(aki));
                final String skistr = new String(Hex.encode(ski));
                final String msg = intres.getLocalizedMessage("createcert.errorpathverifykeyid", akistr,
                        skistr);
                log.error(msg);
                // This will differ if we create link certificates, NewWithOld, therefore we can not throw an exception here.
            }
        }
        final Principal issuerDN = cert.getIssuerX500Principal();
        final Principal caSubjectDN = cacert.getSubjectX500Principal();
        if ((issuerDN != null) && (caSubjectDN != null)) {
            final boolean eq = issuerDN.equals(caSubjectDN);
            if (!eq) {
                final String msg = intres.getLocalizedMessage("createcert.errorpathverifydn",
                        issuerDN.getName(), caSubjectDN.getName());
                log.error(msg);
                throw new CertificateCreateException(msg);
            }
        }
    }
    // Before returning from this method, we will set the private key and provider in the request message, in case the response  message needs to be signed
    if (request != null) {
        request.setResponseKeyInfo(caPrivateKey, provider);
    }
    if (log.isDebugEnabled()) {
        log.debug("X509CA: generated certificate, CA " + this.getCAId() + " for DN: "
                + subject.getCertificateDN());
    }
    return cert;
}

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

License:Open Source License

/**
 * Select the preferred OCSP response sigAlg according to RFC6960 Section 4.4.7 in the following order:
 * /*w  w  w  . j  a  v a2 s.c  o  m*/
 *    1. Select an algorithm specified as a preferred signature algorithm in the client request if it is 
 *       an acceptable algorithm by EJBCA.
 *    2. Select the signature algorithm used to sign a certificate revocation list (CRL) issued by the 
 *       certificate issuer providing status information for the certificate specified by CertID.
 *       (NOT APPLIED)
 *    3. Select the signature algorithm used to sign the OCSPRequest if it is an acceptable algorithm in EJBCA.
 *    4. Select a signature algorithm that has been advertised as being the default signature algorithm for 
 *       the signing service using an out-of-band mechanism.
 *    5. Select a mandatory or recommended signature algorithm specified for the version of OCSP in use, aka. 
 *       specified in the properties file.
 * 
 *    The acceptable algorithm by EJBCA are the algorithms specified in ocsp.properties file in 'ocsp.signaturealgorithm'
 * 
 * @param req
 * @param ocspSigningCacheEntry
 * @param signerCert
 * @return
 */
private String getSigAlg(OCSPReq req, final OcspSigningCacheEntry ocspSigningCacheEntry,
        final X509Certificate signerCert) {
    String sigAlg = null;
    PublicKey pk = signerCert.getPublicKey();
    // Start with the preferred signature algorithm in the OCSP request
    final Extension preferredSigAlgExtension = req
            .getExtension(new ASN1ObjectIdentifier(OCSPObjectIdentifiers.id_pkix_ocsp + ".8"));
    if (preferredSigAlgExtension != null) {
        final ASN1Sequence preferredSignatureAlgorithms = ASN1Sequence
                .getInstance(preferredSigAlgExtension.getParsedValue());
        for (int i = 0; i < preferredSignatureAlgorithms.size(); i++) {
            final ASN1Encodable asn1Encodable = preferredSignatureAlgorithms.getObjectAt(i);
            final ASN1ObjectIdentifier algorithmOid;
            if (asn1Encodable instanceof ASN1ObjectIdentifier) {
                // Handle client requests that were adapted to EJBCA 6.1.0's implementation
                log.info(
                        "OCSP request's PreferredSignatureAlgorithms did not contain an PreferredSignatureAlgorithm, but instead an algorithm OID."
                                + " This will not be supported in a future versions of EJBCA.");
                algorithmOid = (ASN1ObjectIdentifier) asn1Encodable;
            } else {
                // Handle client requests that provide a proper AlgorithmIdentifier as specified in RFC 6960 + RFC 5280
                final ASN1Sequence preferredSignatureAlgorithm = ASN1Sequence.getInstance(asn1Encodable);
                final AlgorithmIdentifier algorithmIdentifier = AlgorithmIdentifier
                        .getInstance(preferredSignatureAlgorithm.getObjectAt(0));
                algorithmOid = algorithmIdentifier.getAlgorithm();
            }
            if (algorithmOid != null) {
                sigAlg = AlgorithmTools.getAlgorithmNameFromOID(algorithmOid);
                if (sigAlg != null && OcspConfiguration.isAcceptedSignatureAlgorithm(sigAlg)
                        && AlgorithmTools.isCompatibleSigAlg(pk, sigAlg)) {
                    if (log.isDebugEnabled()) {
                        log.debug(
                                "Using OCSP response signature algorithm extracted from OCSP request extension. "
                                        + algorithmOid);
                    }
                    return sigAlg;
                }
            }
        }
    }
    // the signature algorithm used to sign the OCSPRequest
    if (req.getSignatureAlgOID() != null) {
        sigAlg = AlgorithmTools.getAlgorithmNameFromOID(req.getSignatureAlgOID());
        if (OcspConfiguration.isAcceptedSignatureAlgorithm(sigAlg)
                && AlgorithmTools.isCompatibleSigAlg(pk, sigAlg)) {
            if (log.isDebugEnabled()) {
                log.debug(
                        "OCSP response signature algorithm: the signature algorithm used to sign the OCSPRequest. "
                                + sigAlg);
            }
            return sigAlg;
        }
    }
    // The signature algorithm that has been advertised as being the default signature algorithm for the signing service using an
    // out-of-band mechanism.
    if (ocspSigningCacheEntry.isUsingSeparateOcspSigningCertificate()) {
        // If we have an OcspKeyBinding we use this configuration to override the default
        sigAlg = ocspSigningCacheEntry.getOcspKeyBinding().getSignatureAlgorithm();
        if (log.isDebugEnabled()) {
            log.debug(
                    "OCSP response signature algorithm: the signature algorithm that has been advertised as being the default signature algorithm "
                            + "for the signing service using an out-of-band mechanism. " + sigAlg);
        }
        return sigAlg;
    }
    // The signature algorithm specified for the version of OCSP in use.
    String sigAlgs = OcspConfiguration.getSignatureAlgorithm();
    sigAlg = getSigningAlgFromAlgSelection(sigAlgs, pk);
    if (log.isDebugEnabled()) {
        log.debug("Using configured signature algorithm to sign OCSP response. " + sigAlg);
    }
    return sigAlg;
}

From source file:org.cesecore.util.CertTools.java

License:Open Source License

public static X509Certificate genSelfCertForPurpose(String dn, long validity, String policyId,
        PrivateKey privKey, PublicKey pubKey, String sigAlg, boolean isCA, int keyusage,
        Date privateKeyNotBefore, Date privateKeyNotAfter, String provider, boolean ldapOrder,
        List<Extension> additionalExtensions)
        throws CertificateParsingException, IOException, OperatorCreationException {
    // Create self signed certificate
    Date firstDate = new Date();

    // Set back startdate ten minutes to avoid some problems with wrongly set clocks.
    firstDate.setTime(firstDate.getTime() - (10 * 60 * 1000));

    Date lastDate = new Date();

    // validity in days = validity*24*60*60*1000 milliseconds
    lastDate.setTime(lastDate.getTime() + (validity * (24 * 60 * 60 * 1000)));

    // Transform the PublicKey to be sure we have it in a format that the X509 certificate generator handles, it might be
    // a CVC public key that is passed as parameter
    PublicKey publicKey = null;//  w  ww .jav a 2 s  .c  om
    if (pubKey instanceof RSAPublicKey) {
        RSAPublicKey rsapk = (RSAPublicKey) pubKey;
        RSAPublicKeySpec rSAPublicKeySpec = new RSAPublicKeySpec(rsapk.getModulus(), rsapk.getPublicExponent());
        try {
            publicKey = KeyFactory.getInstance("RSA").generatePublic(rSAPublicKeySpec);
        } catch (InvalidKeySpecException e) {
            log.error("Error creating RSAPublicKey from spec: ", e);
            publicKey = pubKey;
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException("RSA was not a known algorithm", e);
        }
    } else if (pubKey instanceof ECPublicKey) {
        ECPublicKey ecpk = (ECPublicKey) pubKey;
        try {
            ECPublicKeySpec ecspec = new ECPublicKeySpec(ecpk.getW(), ecpk.getParams()); // will throw NPE if key is "implicitlyCA"
            final String algo = ecpk.getAlgorithm();
            if (algo.equals(AlgorithmConstants.KEYALGORITHM_ECGOST3410)) {
                try {
                    publicKey = KeyFactory.getInstance("ECGOST3410").generatePublic(ecspec);
                } catch (NoSuchAlgorithmException e) {
                    throw new IllegalStateException("ECGOST3410 was not a known algorithm", e);
                }
            } else if (algo.equals(AlgorithmConstants.KEYALGORITHM_DSTU4145)) {
                try {
                    publicKey = KeyFactory.getInstance("DSTU4145").generatePublic(ecspec);
                } catch (NoSuchAlgorithmException e) {
                    throw new IllegalStateException("DSTU4145 was not a known algorithm", e);
                }
            } else {
                try {
                    publicKey = KeyFactory.getInstance("EC").generatePublic(ecspec);
                } catch (NoSuchAlgorithmException e) {
                    throw new IllegalStateException("EC was not a known algorithm", e);
                }
            }
        } catch (InvalidKeySpecException e) {
            log.error("Error creating ECPublicKey from spec: ", e);
            publicKey = pubKey;
        } catch (NullPointerException e) {
            log.debug("NullPointerException, probably it is implicitlyCA generated keys: " + e.getMessage());
            publicKey = pubKey;
        }
    } else {
        log.debug("Not converting key of class. " + pubKey.getClass().getName());
        publicKey = pubKey;
    }

    // Serialnumber is random bits, where random generator is initialized with Date.getTime() when this
    // bean is created.
    byte[] serno = new byte[8];
    SecureRandom random;
    try {
        random = SecureRandom.getInstance("SHA1PRNG");
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException("SHA1PRNG was not a known algorithm", e);
    }
    random.setSeed(new Date().getTime());
    random.nextBytes(serno);

    SubjectPublicKeyInfo pkinfo;
    try {
        pkinfo = new SubjectPublicKeyInfo((ASN1Sequence) ASN1Primitive.fromByteArray(publicKey.getEncoded()));
    } catch (IOException e) {
        throw new IllegalArgumentException("Provided public key could not be read to ASN1Primitive", e);
    }
    X509v3CertificateBuilder certbuilder = new X509v3CertificateBuilder(
            CertTools.stringToBcX500Name(dn, ldapOrder), new BigInteger(serno).abs(), firstDate, lastDate,
            CertTools.stringToBcX500Name(dn, ldapOrder), pkinfo);

    // Basic constranits is always critical and MUST be present at-least in CA-certificates.
    BasicConstraints bc = new BasicConstraints(isCA);
    certbuilder.addExtension(Extension.basicConstraints, true, bc);

    // Put critical KeyUsage in CA-certificates
    if (isCA || keyusage != 0) {
        X509KeyUsage ku = new X509KeyUsage(keyusage);
        certbuilder.addExtension(Extension.keyUsage, true, ku);
    }

    if ((privateKeyNotBefore != null) || (privateKeyNotAfter != null)) {
        final ASN1EncodableVector v = new ASN1EncodableVector();
        if (privateKeyNotBefore != null) {
            v.add(new DERTaggedObject(false, 0, new DERGeneralizedTime(privateKeyNotBefore)));
        }
        if (privateKeyNotAfter != null) {
            v.add(new DERTaggedObject(false, 1, new DERGeneralizedTime(privateKeyNotAfter)));
        }
        certbuilder.addExtension(Extension.privateKeyUsagePeriod, false, new DERSequence(v));
    }

    // Subject and Authority key identifier is always non-critical and MUST be present for certificates to verify in Firefox.
    try {
        if (isCA) {

            ASN1InputStream sAsn1InputStream = new ASN1InputStream(
                    new ByteArrayInputStream(publicKey.getEncoded()));
            ASN1InputStream aAsn1InputStream = new ASN1InputStream(
                    new ByteArrayInputStream(publicKey.getEncoded()));
            try {
                SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo(
                        (ASN1Sequence) sAsn1InputStream.readObject());
                X509ExtensionUtils x509ExtensionUtils = new BcX509ExtensionUtils();
                SubjectKeyIdentifier ski = x509ExtensionUtils.createSubjectKeyIdentifier(spki);
                SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo(
                        (ASN1Sequence) aAsn1InputStream.readObject());
                AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki);

                certbuilder.addExtension(Extension.subjectKeyIdentifier, false, ski);
                certbuilder.addExtension(Extension.authorityKeyIdentifier, false, aki);
            } finally {
                sAsn1InputStream.close();
                aAsn1InputStream.close();
            }
        }
    } catch (IOException e) { // do nothing
    }

    // CertificatePolicies extension if supplied policy ID, always non-critical
    if (policyId != null) {
        PolicyInformation pi = new PolicyInformation(new ASN1ObjectIdentifier(policyId));
        DERSequence seq = new DERSequence(pi);
        certbuilder.addExtension(Extension.certificatePolicies, false, seq);
    }
    // Add any additional
    if (additionalExtensions != null) {
        for (final Extension extension : additionalExtensions) {
            certbuilder.addExtension(extension.getExtnId(), extension.isCritical(), extension.getParsedValue());
        }
    }
    final ContentSigner signer = new BufferingContentSigner(
            new JcaContentSignerBuilder(sigAlg).setProvider(provider).build(privKey), 20480);
    final X509CertificateHolder certHolder = certbuilder.build(signer);
    final X509Certificate selfcert = (X509Certificate) CertTools.getCertfromByteArray(certHolder.getEncoded());

    return selfcert;
}

From source file:org.cesecore.util.CertTools.java

License:Open Source License

/**
 * Gets an altName string from an X509Extension
 * //from   ww w. java 2s .c om
 * @param ext X509Extension with AlternativeNames
 * @return String as defined in method getSubjectAlternativeName
 */
public static String getAltNameStringFromExtension(Extension ext) {
    String altName = null;
    // GeneralNames
    ASN1Encodable gnames = ext.getParsedValue();
    if (gnames != null) {
        try {
            GeneralNames names = GeneralNames.getInstance(gnames);
            GeneralName[] gns = names.getNames();
            for (GeneralName gn : gns) {
                int tag = gn.getTagNo();
                ASN1Encodable name = gn.getName();
                String str = CertTools.getGeneralNameString(tag, name);
                if (str == null) {
                    continue;
                }
                if (altName == null) {
                    altName = str;
                } else {
                    altName += ", " + str;
                }
            }
        } catch (IOException e) {
            log.error("IOException parsing altNames: ", e);
            return null;
        }
    }
    return altName;
}

From source file:org.codice.ddf.security.certificate.generator.CertificateCommandTest.java

License:Open Source License

private static void validateSans(KeyStoreFile ksf, String alias, boolean withAdditionalSans) throws Exception {
    final KeyStore.Entry ke = ksf.getEntry(alias);
    assertThat(ke, instanceOf(KeyStore.PrivateKeyEntry.class));

    final KeyStore.PrivateKeyEntry pke = (KeyStore.PrivateKeyEntry) ke;
    final Certificate c = pke.getCertificate();
    final X509CertificateHolder holder = new X509CertificateHolder(c.getEncoded());
    final Extension csn = holder.getExtension(Extension.subjectAlternativeName);

    assertThat(csn.getParsedValue().toASN1Primitive().getEncoded(ASN1Encoding.DER),
            equalTo(expectedSanGeneralName(alias, withAdditionalSans)));
}

From source file:org.codice.ddf.security.certificate.generator.CertificateSigningRequestTest.java

License:Open Source License

@Test
public void testNewCertificateBuilderWithSan() throws Exception {
    final DateTime start = DateTime.now().minusDays(1);
    final DateTime end = start.plusYears(100);
    final KeyPair kp = makeKeyPair();

    csr.setSerialNumber(1);/*from   w w w .  j  av  a 2  s .co  m*/
    csr.setNotBefore(start);
    csr.setNotAfter(end);
    csr.setCommonName("A");
    csr.setSubjectKeyPair(kp);
    csr.addSubjectAlternativeNames("IP:1.2.3.4", "DNS:A");
    final X509Certificate issuerCert = mock(X509Certificate.class);

    doReturn(new X500Principal("CN=Duke, OU=JavaSoft, O=Sun Microsystems, C=US")).when(issuerCert)
            .getSubjectX500Principal();
    final JcaX509v3CertificateBuilder builder = csr.newCertificateBuilder(issuerCert);
    final X509CertificateHolder holder = builder.build(new DemoCertificateAuthority().getContentSigner());

    assertThat(holder.getSerialNumber(), equalTo(BigInteger.ONE));
    assertThat(holder.getNotBefore(), equalTo(new Time(start.toDate()).getDate()));
    assertThat(holder.getNotAfter(), equalTo(new Time(end.toDate()).getDate()));
    assertThat(holder.getSubject().toString(), equalTo("cn=A"));
    assertThat("Unable to validate public key", holder.getSubjectPublicKeyInfo(),
            equalTo(SubjectPublicKeyInfo.getInstance(kp.getPublic().getEncoded())));
    final org.bouncycastle.asn1.x509.Extension csn = holder
            .getExtension(org.bouncycastle.asn1.x509.Extension.subjectAlternativeName);

    assertThat(csn.getParsedValue().toASN1Primitive().getEncoded(ASN1Encoding.DER),
            equalTo(new GeneralNamesBuilder().addName(new GeneralName(GeneralName.iPAddress, "1.2.3.4"))
                    .addName(new GeneralName(GeneralName.dNSName, "A")).build().getEncoded(ASN1Encoding.DER)));
}

From source file:org.cryptable.pki.communication.PKICMPMessages.java

License:Open Source License

/**
 * Creates a certification request//from w w  w .j av a 2 s  .c  o  m
 *
 * @param distinguishedName the distinguished name for the certificate
 * @param keyPair the key pair to certify, you have to remove the private key so the CA won't archive it
 * @return return the binary ASN.1 message for a certification request
 * @throws CertificateEncodingException
 * @throws CMSException
 * @throws CRMFException
 * @throws OperatorCreationException
 * @throws CMPException
 * @throws IOException
 */
private byte[] createCertificateMessage(String distinguishedName, KeyPair keyPair, int requestType)
        throws CertificateEncodingException, CMSException, CRMFException, OperatorCreationException,
        CMPException, IOException, PKICMPMessageException, NoSuchFieldException, IllegalAccessException {

    JcaCertificateRequestMessageBuilder certReqBuild = new JcaCertificateRequestMessageBuilder(BigInteger.ZERO);

    // Basic certificate requests
    certReqBuild.setSubject(new X500Name(distinguishedName));

    // Add key pair
    if (keyPair != null) {
        byte[] bRSAKey = keyPair.getPublic().getEncoded();
        certReqBuild.setPublicKey(new SubjectPublicKeyInfo(ASN1Sequence.getInstance(bRSAKey)));
        if (keyPair.getPrivate() != null) {
            certReqBuild.addControl(
                    new JcaPKIArchiveControlBuilder(keyPair.getPrivate(), new X500Principal(distinguishedName))
                            .addRecipientGenerator(
                                    new JceKeyTransRecipientInfoGenerator(pkiKeyStore.getRecipientCertificate())
                                            .setProvider(pkiKeyStore.getProvider()))
                            .build(new JceCMSContentEncryptorBuilder(
                                    new ASN1ObjectIdentifier(CMSEnvelopedDataGenerator.DES_EDE3_CBC))
                                            .setProvider(pkiKeyStore.getProvider()).build()));
        }
    }

    if (optionalValidity != null) {
        Field field = certReqBuild.getClass().getSuperclass().getDeclaredField("templateBuilder");
        field.setAccessible(true);
        CertTemplateBuilder certTemplateBuilder = (CertTemplateBuilder) field.get(certReqBuild);
        certTemplateBuilder.setValidity(optionalValidity);
    }

    if (extensions != null) {
        for (Extension extension : extensions)
            certReqBuild.addExtension(extension.getExtnId(), extension.isCritical(),
                    extension.getParsedValue());
    }

    CertReqMessages certReqMsgs = new CertReqMessages(certReqBuild.build().toASN1Structure());

    return createProtectedPKIMessage(new PKIBody(requestType, certReqMsgs));
}