Example usage for java.security.cert CertificateEncodingException getMessage

List of usage examples for java.security.cert CertificateEncodingException getMessage

Introduction

In this page you can find the example usage for java.security.cert CertificateEncodingException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:be.fedict.eid.tsl.TrustServiceList.java

public void addOtherTSLPointer(String location, String mimeType, String tslType, String schemeTerritory,
        String schemeOperatorName, String schemeTypeCommunityRuleUri, Locale schemeTypeCommunityRuleUriLocale,
        X509Certificate digitalIdentityCertificate) {
    TSLSchemeInformationType schemeInformation = getSchemeInformation();
    OtherTSLPointersType otherTSLPointers = schemeInformation.getPointersToOtherTSL();
    if (null == otherTSLPointers) {
        otherTSLPointers = this.objectFactory.createOtherTSLPointersType();
        schemeInformation.setPointersToOtherTSL(otherTSLPointers);
    }//from   w  w w . jav  a2 s . c om
    List<OtherTSLPointerType> pointerList = otherTSLPointers.getOtherTSLPointer();
    OtherTSLPointerType otherTSLPointer = this.objectFactory.createOtherTSLPointerType();
    pointerList.add(otherTSLPointer);

    otherTSLPointer.setTSLLocation(location);
    AdditionalInformationType additionalInformation = this.objectFactory.createAdditionalInformationType();
    otherTSLPointer.setAdditionalInformation(additionalInformation);

    List<Object> objects = additionalInformation.getTextualInformationOrOtherInformation();
    {
        JAXBElement<String> mimeTypeElement = this.tslxObjectFactory.createMimeType(mimeType);
        AnyType anyType = this.objectFactory.createAnyType();
        anyType.getContent().add(mimeTypeElement);
        objects.add(anyType);
    }
    {
        JAXBElement<String> tslTypeElement = this.objectFactory.createTSLType(tslType);
        AnyType anyType = this.objectFactory.createAnyType();
        anyType.getContent().add(tslTypeElement);
        objects.add(anyType);
    }
    {
        JAXBElement<String> schemeTerritoryElement = this.objectFactory.createSchemeTerritory(schemeTerritory);
        AnyType anyType = this.objectFactory.createAnyType();
        anyType.getContent().add(schemeTerritoryElement);
        objects.add(anyType);
    }
    {
        InternationalNamesType i18nNames = this.objectFactory.createInternationalNamesType();
        MultiLangNormStringType i18nName = this.objectFactory.createMultiLangNormStringType();
        i18nName.setLang("en");
        i18nName.setValue(schemeOperatorName);
        i18nNames.getName().add(i18nName);
        JAXBElement<InternationalNamesType> schemeOperatorNameElement = this.objectFactory
                .createSchemeOperatorName(i18nNames);
        AnyType anyType = this.objectFactory.createAnyType();
        anyType.getContent().add(schemeOperatorNameElement);
        objects.add(anyType);
    }
    {
        NonEmptyMultiLangURIListType uriList = this.objectFactory.createNonEmptyMultiLangURIListType();
        NonEmptyMultiLangURIType uri = this.objectFactory.createNonEmptyMultiLangURIType();
        uri.setLang(schemeTypeCommunityRuleUriLocale.getLanguage());
        uri.setValue(schemeTypeCommunityRuleUri);
        uriList.getURI().add(uri);
        JAXBElement<NonEmptyMultiLangURIListType> schemeTypeCommunityRulesElement = this.objectFactory
                .createSchemeTypeCommunityRules(uriList);
        AnyType anyType = this.objectFactory.createAnyType();
        anyType.getContent().add(schemeTypeCommunityRulesElement);
        objects.add(anyType);
    }
    if (null != digitalIdentityCertificate) {
        ServiceDigitalIdentityListType serviceDigitalIdentityList = this.objectFactory
                .createServiceDigitalIdentityListType();
        DigitalIdentityListType digitalIdentityList = this.objectFactory.createDigitalIdentityListType();
        List<DigitalIdentityType> digitalIdentities = digitalIdentityList.getDigitalId();
        DigitalIdentityType digitalIdentity = this.objectFactory.createDigitalIdentityType();

        try {
            digitalIdentity.setX509Certificate(digitalIdentityCertificate.getEncoded());
        } catch (CertificateEncodingException e) {
            throw new RuntimeException("X509 encoding error: " + e.getMessage(), e);
        }
        digitalIdentities.add(digitalIdentity);

        digitalIdentity = this.objectFactory.createDigitalIdentityType();
        digitalIdentity.setX509SubjectName(digitalIdentityCertificate.getSubjectX500Principal().getName());
        digitalIdentities.add(digitalIdentity);

        byte[] skiValue = digitalIdentityCertificate
                .getExtensionValue(X509Extensions.SubjectKeyIdentifier.getId());
        if (null != skiValue) {
            digitalIdentity = this.objectFactory.createDigitalIdentityType();
            SubjectKeyIdentifierStructure subjectKeyIdentifierStructure;
            try {
                subjectKeyIdentifierStructure = new SubjectKeyIdentifierStructure(skiValue);
            } catch (IOException e) {
                throw new RuntimeException("X509 SKI decoding error: " + e.getMessage(), e);
            }
            digitalIdentity.setX509SKI(subjectKeyIdentifierStructure.getKeyIdentifier());
            digitalIdentities.add(digitalIdentity);
        }

        List<DigitalIdentityListType> digitalIdentityListList = serviceDigitalIdentityList
                .getServiceDigitalIdentity();
        digitalIdentityListList.add(digitalIdentityList);

        otherTSLPointer.setServiceDigitalIdentities(serviceDigitalIdentityList);
    }
}

From source file:org.ejbca.ui.web.pub.CertDistServlet.java

private void handleCaChainCommands(AuthenticationToken administrator, String issuerdn, int caid, String format,
        HttpServletResponse res) throws IOException, NoSuchFieldException {
    try {// www  .  j ava2  s .  c o m
        Certificate[] chain = getCertificateChain(administrator, caid, issuerdn);
        // Reverse the chain to get proper ordering for chain file
        // (top-level CA first, requested CA last).
        ArrayUtils.reverse(chain);

        // Construct the filename based on requested CA. Fail-back to
        // name "ca-chain.EXT".
        String filename = RequestHelper.getFileNameFromCertNoEnding(chain[chain.length - 1], "ca") + "-chain."
                + format.toLowerCase();

        byte[] outbytes = new byte[0];
        // Encode and send back
        if ((format == null) || StringUtils.equalsIgnoreCase(format, "pem")) {
            outbytes = CertTools.getPemFromCertificateChain(Arrays.asList(chain));
        } else {
            // Create a JKS truststore with the CA certificates in
            final KeyStore store = KeyStore.getInstance("JKS");
            store.load(null, null);
            for (int i = 0; i < chain.length; i++) {
                String cadn = CertTools.getSubjectDN(chain[i]);
                String alias = CertTools.getPartFromDN(cadn, "CN");
                if (alias == null) {
                    alias = CertTools.getPartFromDN(cadn, "O");
                }
                if (alias == null) {
                    alias = "cacert" + i;
                }
                alias = StringUtils.replaceChars(alias, ' ', '_');
                alias = StringUtils.substring(alias, 0, 15);
                store.setCertificateEntry(alias, chain[i]);
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                store.store(out, "changeit".toCharArray());
                out.close();
                outbytes = out.toByteArray();
            }
        }
        // We must remove cache headers for IE
        ServletUtils.removeCacheHeaders(res);
        res.setHeader("Content-disposition",
                "attachment; filename=\"" + StringTools.stripFilename(filename) + "\"");
        res.setContentType("application/octet-stream");
        res.setContentLength(outbytes.length);
        res.getOutputStream().write(outbytes);
        log.debug("Sent CA certificate chain to client, len=" + outbytes.length + ".");
    } catch (CertificateEncodingException e) {
        log.debug("Error getting CA certificate chain: ", e);
        res.sendError(HttpServletResponse.SC_NOT_FOUND, "Error getting CA certificate chain.");
    } catch (KeyStoreException e) {
        log.debug("Error creating JKS with CA certificate chain: ", e);
        res.sendError(HttpServletResponse.SC_NOT_FOUND, "Error creating JKS with CA certificate chain.");
    } catch (NoSuchAlgorithmException e) {
        log.debug("Error creating JKS with CA certificate chain: ", e);
        res.sendError(HttpServletResponse.SC_NOT_FOUND, "Error creating JKS with CA certificate chain.");
    } catch (CertificateException e) {
        log.debug("Error creating JKS with CA certificate chain: ", e);
        res.sendError(HttpServletResponse.SC_NOT_FOUND, "Error creating JKS with CA certificate chain.");
    } catch (EJBException e) {
        log.debug("CA does not exist: ", e);
        res.sendError(HttpServletResponse.SC_NOT_FOUND,
                "CA does not exist: " + HTMLTools.htmlescape(e.getMessage()));
    } catch (AuthorizationDeniedException e) {
        log.debug("Authotization denied: ", e);
        res.sendError(HttpServletResponse.SC_UNAUTHORIZED,
                "Authorization denied: " + HTMLTools.htmlescape(e.getMessage()));
    }
}

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

@Override
public String healthCheck() {
    final StringBuilder sb = new StringBuilder();
    // Check that there are no ACTIVE OcspKeyBindings that are not in the cache before checking usability..
    for (InternalKeyBindingInfo internalKeyBindingInfo : internalKeyBindingMgmtSession
            .getAllInternalKeyBindingInfos(OcspKeyBinding.IMPLEMENTATION_ALIAS)) {
        if (internalKeyBindingInfo.getStatus().equals(InternalKeyBindingStatus.ACTIVE)) {
            final Certificate ocspCertificate = certificateStoreSession
                    .findCertificateByFingerprint(internalKeyBindingInfo.getCertificateId());
            final X509Certificate issuingCertificate = certificateStoreSession
                    .findLatestX509CertificateBySubject(CertTools.getIssuerDN(ocspCertificate));
            OcspSigningCacheEntry ocspSigningCacheEntry = null;
            if (issuingCertificate != null) {
                final List<CertificateID> certIds = OcspSigningCache
                        .getCertificateIDFromCertificate(issuingCertificate);
                // We only need to use the first certId type to find an entry in the cache, certIds.get(0), since all of them should be in the cache
                ocspSigningCacheEntry = OcspSigningCache.INSTANCE.getEntry(certIds.get(0));
                if (ocspSigningCacheEntry == null) {
                    //Could be a cache issue?
                    try {
                        ocspSigningCacheEntry = findAndAddMissingCacheEntry(certIds.get(0));
                    } catch (CertificateEncodingException e) {
                        throw new IllegalStateException("Could not process certificate", e);
                    }/*w  w w.java2  s  .c  om*/
                }
            } else {
                log.info("Can not find issuer certificate from subject DN '"
                        + CertTools.getIssuerDN(ocspCertificate) + "'.");
            }

            if (ocspSigningCacheEntry == null) {
                final String errMsg = intres.getLocalizedMessage("ocsp.signingkeynotincache",
                        internalKeyBindingInfo.getName());
                sb.append('\n').append(errMsg);
                log.error(errMsg);
            }
        }
    }
    if (!sb.toString().equals("")) {
        return sb.toString();
    }
    try {
        final Collection<OcspSigningCacheEntry> ocspSigningCacheEntries = OcspSigningCache.INSTANCE
                .getEntries();
        if (ocspSigningCacheEntries.isEmpty()) {
            // Only report this in the server log. It is not an erroneous state to have no ACTIVE OcspKeyBindings.
            if (log.isDebugEnabled()) {
                log.debug(intres.getLocalizedMessage("ocsp.errornosignkeys"));
            }
        } else {
            for (OcspSigningCacheEntry ocspSigningCacheEntry : ocspSigningCacheEntries) {
                // Only verify non-CA responders
                final X509Certificate ocspSigningCertificate = ocspSigningCacheEntry
                        .getOcspSigningCertificate();
                if (ocspSigningCertificate == null) {
                    continue;
                }
                final String subjectDn = CertTools
                        .getSubjectDN(ocspSigningCacheEntry.getCaCertificateChain().get(0));
                final String serialNumberForLog = CertTools
                        .getSerialNumberAsString(ocspSigningCacheEntry.getOcspSigningCertificate());
                final String errMsg = intres.getLocalizedMessage("ocsp.errorocspkeynotusable", subjectDn,
                        serialNumberForLog);
                final PrivateKey privateKey = ocspSigningCacheEntry.getPrivateKey();
                if (privateKey == null) {
                    sb.append('\n').append(errMsg);
                    log.error("No key available. " + errMsg);
                    continue;
                }
                if (OcspConfiguration.getHealthCheckCertificateValidity()
                        && !CertTools.isCertificateValid(ocspSigningCertificate)) {
                    sb.append('\n').append(errMsg);
                    continue;
                }
                if (OcspConfiguration.getHealthCheckSignTest()) {
                    try {
                        final String providerName = ocspSigningCacheEntry.getSignatureProviderName();
                        KeyTools.testKey(privateKey, ocspSigningCertificate.getPublicKey(), providerName);
                    } catch (InvalidKeyException e) {
                        // thrown by testKey
                        sb.append('\n').append(errMsg);
                        log.error("Key not working. SubjectDN '" + subjectDn + "'. Error comment '" + errMsg
                                + "'. Message '" + e.getMessage());
                        continue;
                    }
                }
                if (log.isDebugEnabled()) {
                    final String name = ocspSigningCacheEntry.getOcspKeyBinding().getName();
                    log.debug("Test of \"" + name + "\" OK!");
                }
            }
        }
    } catch (Exception e) {
        final String errMsg = intres.getLocalizedMessage("ocsp.errorloadsigningcerts");
        log.error(errMsg, e);
        sb.append(errMsg).append(": ").append(errMsg);
    }
    return sb.toString();
}