Example usage for java.security.cert CertificateException getMessage

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

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:org.signserver.admin.cli.defaultimpl.token.QueryTokenEntriesCommand.java

private void renderEntry(int i, TokenEntry entry, boolean verbose) {
    getOutputStream().println(i + ": " + entry.getAlias());
    if (verbose) {
        final StringBuilder sb = new StringBuilder();
        sb.append(INDENT).append("Type: ").append(entry.getType()).append("\n");
        if (entry.getCreationDate() != null) {
            sb.append(INDENT).append("Creation date: ").append(entry.getCreationDate()).append("\n");
        }//from   w w w .  j  av a  2s.c  o  m
        try {
            if (entry.getParsedChain() != null) {
                sb.append(INDENT).append("Certificate chain: ").append("\n")
                        .append(Arrays.toString(entry.getParsedChain())).append("\n");
            }
        } catch (CertificateException ex) {
            sb.append(INDENT).append("Certificate chain: ").append("Unable to parse: ").append(ex.getMessage())
                    .append("\n");
        }
        try {
            if (entry.getParsedTrustedCertificate() != null) {
                sb.append(INDENT).append("Trusted certificate: ").append("\n")
                        .append(entry.getParsedTrustedCertificate()).append("\n");
            }
        } catch (CertificateException ex) {
            sb.append(INDENT).append("Trusted certificate: ").append("Unable to parse: ")
                    .append(ex.getMessage()).append("\n");
        }
        if (entry.getInfo() != null && !entry.getInfo().isEmpty()) {
            sb.append(INDENT).append("Additional information:\n");
            for (Map.Entry<String, String> info : entry.getInfo().entrySet()) {
                sb.append(INDENT).append(INDENT).append(info.getKey()).append(": ").append(info.getValue())
                        .append("\n");
            }
        }
        sb.append("\n");
        getOutputStream().println(sb.toString());
    }
}

From source file:cc.abstra.trantor.security.ssl.OwnSSLProtocolSocketFactory.java

/**
 * Describe <code>verifyHostname</code> method here.
 *
 * @param socket a <code>SSLSocket</code> value
 * @exception SSLPeerUnverifiedException  If there are problems obtaining
 * the server certificates from the SSL session, or the server host name 
 * does not match with the "Common Name" in the server certificates 
 * SubjectDN.// ww w  . ja  va  2 s  .co  m
 * @exception UnknownHostException  If we are not able to resolve
 * the SSL sessions returned server host name. 
 */
private void verifyHostname(SSLSocket socket) throws SSLPeerUnverifiedException, UnknownHostException {
    if (sslManager == null) {
        return;
    }
    ISSLErrorManager errorMng = sslManager.getSSLErrorManager();
    if (errorMng == null) {
        return;
    }

    SSLSession session = socket.getSession();
    String hostname = session.getPeerHost();
    try {
        InetAddress.getByName(hostname);
    } catch (UnknownHostException uhe) {
        throw new UnknownHostException("Could not resolve SSL sessions " + "server hostname: " + hostname);
    }

    X509Certificate[] certs = session.getPeerCertificateChain();
    if (certs == null || certs.length == 0)
        throw new SSLPeerUnverifiedException("No server certificates found!");

    //get the servers DN in its string representation
    String dn = certs[0].getSubjectDN().getName();

    //might be useful to print out all certificates we receive from the
    //server, in case one has to debug a problem with the installed certs.
    if (LOG.isDebugEnabled()) {
        LOG.debug("Server certificate chain:");
        for (int i = 0; i < certs.length; i++) {
            LOG.debug("X509Certificate[" + i + "]=" + certs[i]);
        }
    }
    //get the common name from the first cert
    String cn = getCN(dn);
    if (hostname.equalsIgnoreCase(cn)) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Target hostname valid: " + cn);
        }
    } else {
        try {
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            java.security.cert.X509Certificate servCert = (java.security.cert.X509Certificate) cf
                    .generateCertificate(new ByteArrayInputStream(certs[0].getEncoded()));
            if (!errorMng.continueErrorPeer(hostname, servCert)) {
                throw new SSLPeerUnverifiedException(
                        "HTTPS hostname invalid: expected '" + hostname + "', received '" + cn + "'");
            }
        } catch (CertificateException ex) {
            LOG.error(ex.getMessage(), ex);
            throw new SSLPeerUnverifiedException(
                    "Unexpected error checking HTTPS hostname: " + ex.getMessage());
        } catch (CertificateEncodingException ex) {
            LOG.error(ex.getMessage(), ex);
            throw new SSLPeerUnverifiedException(
                    "Unexpected error checking HTTPS hostname: " + ex.getMessage());
        }
    }
}

From source file:be.fedict.eid.dss.protocol.simple.SimpleDSSProtocolService.java

public void init(ServletContext servletContext, DSSProtocolContext dssContext) {
    LOG.debug("init");
    this.dssContext = dssContext;

    try {/*  w  w  w .  j  a va  2s .  c om*/
        this.certificateFactory = CertificateFactory.getInstance("X.509");
    } catch (CertificateException e) {
        throw new RuntimeException("could not create certificate factory instance: " + e.getMessage(), e);
    }
}

From source file:edu.vt.middleware.crypt.CryptProvider.java

/**
 * <p>This creates a <code>CertificateFactory</code> using the supplied type
 * name.</p>/*from  ww w .java 2  s. co  m*/
 *
 * @param  type  <code>String</code>
 *
 * @return  <code>CertificateFactory</code>
 *
 * @throws  CryptException  if the type is not available from any provider or
 * the provider is not available in the environment
 */
public static CertificateFactory getCertificateFactory(final String type) throws CryptException {
    final Log logger = LogFactory.getLog(CryptProvider.class);
    CertificateFactory cf = null;
    for (int i = 0; i < providers.length; i++) {
        try {
            cf = CertificateFactory.getInstance(type, providers[i]);
        } catch (CertificateException e) {
            if (logger.isDebugEnabled()) {
                logger.debug(
                        "Could not get instance of certificate factory type " + type + " from " + providers[i]);
            }
        } catch (NoSuchProviderException e) {
            if (logger.isDebugEnabled()) {
                logger.debug("Could not find provider " + providers[i]);
            }
        } finally {
            if (cf != null) {
                break;
            }
        }
    }
    if (cf == null) {
        try {
            cf = CertificateFactory.getInstance(type);
        } catch (CertificateException e) {
            if (logger.isDebugEnabled()) {
                logger.debug("Could not get instance of certificate factory type " + type);
            }
            throw new CryptException(e.getMessage());
        }
    }
    return cf;
}

From source file:com.appdynamics.monitors.azure.statsCollector.AzureServiceBusStatsCollector.java

private KeyStore getKeyStore(String keyStoreName, String password) {
    KeyStore ks = null;/* ww w.j ava  2s  . com*/
    FileInputStream fis = null;
    try {
        ks = KeyStore.getInstance("JKS");
        char[] passwordArray = password.toCharArray();
        fis = new java.io.FileInputStream(keyStoreName);
        ks.load(fis, passwordArray);
        fis.close();

    } catch (CertificateException e) {
        logger.error(e.getMessage(), e);
        throw new RuntimeException(e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
        logger.error(e.getMessage(), e);
        throw new RuntimeException(e.getMessage(), e);
    } catch (KeyStoreException e) {
        logger.error(e.getMessage(), e);
        throw new RuntimeException(e.getMessage(), e);
    } catch (FileNotFoundException e) {
        logger.error(e.getMessage(), e);
        throw new RuntimeException(e.getMessage(), e);
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        throw new RuntimeException(e.getMessage(), e);
    } finally {
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
        }
    }
    return ks;
}

From source file:be.fedict.trust.client.ServerCrypto.java

public X509Certificate loadCertificate(InputStream in) throws WSSecurityException {
    LOG.debug("loadCertificate");
    CertificateFactory certificateFactory;
    try {/*ww w  .  jav  a2  s . c o  m*/
        certificateFactory = CertificateFactory.getInstance("X.509");
    } catch (CertificateException e) {
        throw new WSSecurityException("X509 algo", e);
    }
    X509Certificate certificate;
    try {
        certificate = (X509Certificate) certificateFactory.generateCertificate(in);
    } catch (CertificateException e) {
        throw new WSSecurityException("X509 error: " + e.getMessage(), e);
    }
    if (null == this.certificate) {
        LOG.debug("trusting incoming certificate as is");
        this.certificate = certificate;
    }
    return certificate;
}

From source file:org.ejbca.core.protocol.ocsp.extension.unid.OCSPUnidExtension.java

@Override
public void init() {
    // DataSource
    dataSourceJndi = OcspConfiguration.getUnidDataSource();
    if (StringUtils.isEmpty(dataSourceJndi)) {
        String errMsg = intres.getLocalizedMessage("ocsp.errornoinitparam", "unidDataSource");
        m_log.error(errMsg);/*  w ww.  j  a  va2 s  .co  m*/
        throw new IllegalArgumentException(errMsg);
    }
    String trustDir = OcspConfiguration.getUnidTrustDir();
    if (StringUtils.isEmpty(trustDir)) {
        String errMsg = intres.getLocalizedMessage("ocsp.errornoinitparam", "unidTrustDir");
        m_log.error(errMsg);
        throw new IllegalArgumentException(errMsg);
    }
    // read all files from trustDir, expect that they are PEM formatted certificates
    CryptoProviderTools.installBCProviderIfNotAvailable();
    File dir = new File(trustDir);
    try {
        if (dir == null || dir.isDirectory() == false) {
            m_log.error(dir.getCanonicalPath() + " is not a directory.");
            throw new IllegalArgumentException(dir.getCanonicalPath() + " is not a directory.");
        }
        File files[] = dir.listFiles();
        if (files == null || files.length == 0) {
            String errMsg = intres.getLocalizedMessage("ocsp.errornotrustfiles", dir.getCanonicalPath());
            m_log.error(errMsg);
        }
        for (int i = 0; i < files.length; i++) {
            final String fileName = files[i].getCanonicalPath();
            // Read the file, don't stop completely if one file has errors in it
            try {
                final byte bFromFile[] = FileTools.readFiletoBuffer(fileName);
                byte[] bytes;
                try {
                    bytes = FileTools.getBytesFromPEM(bFromFile, CertTools.BEGIN_CERTIFICATE,
                            CertTools.END_CERTIFICATE);
                } catch (Exception t) {
                    bytes = bFromFile; // assume binary data (.der)
                }
                final X509Certificate cert = (X509Certificate) CertTools.getCertfromByteArray(bytes);
                this.trustedCerts.add(cert.getSerialNumber());
            } catch (CertificateException e) {
                String errMsg = intres.getLocalizedMessage("ocsp.errorreadingfile", fileName, "trustDir",
                        e.getMessage());
                m_log.error(errMsg, e);
            } catch (IOException e) {
                String errMsg = intres.getLocalizedMessage("ocsp.errorreadingfile", fileName, "trustDir",
                        e.getMessage());
                m_log.error(errMsg, e);
            }
        }
    } catch (IOException e) {
        String errMsg = intres.getLocalizedMessage("ocsp.errorreadingtrustfiles", e.getMessage());
        m_log.error(errMsg, e);
        throw new IllegalArgumentException(errMsg);
    }
    String cacertfile = OcspConfiguration.getUnidCaCert();
    if (StringUtils.isEmpty(cacertfile)) {
        String errMsg = intres.getLocalizedMessage("ocsp.errornoinitparam", "unidCACert");
        m_log.error(errMsg);
        throw new IllegalArgumentException(errMsg);
    }
    try {
        byte[] bytes = FileTools.getBytesFromPEM(FileTools.readFiletoBuffer(cacertfile),
                CertTools.BEGIN_CERTIFICATE, CertTools.END_CERTIFICATE);
        cacert = CertTools.getCertfromByteArray(bytes);
    } catch (Exception e) {
        String errMsg = intres.getLocalizedMessage("ocsp.errorreadingfile", "file", "cacertfile",
                e.getMessage());
        m_log.error(errMsg, e);
        throw new IllegalArgumentException(errMsg);
    }

}

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

/** Called after construction
 * //from  w  w  w  .  ja v a  2 s .c om
 * @param config ServletConfig that can be used to read init-params from web-xml
 */
public void init(ServletConfig config) {
    // DataSource
    dataSourceJndi = OcspConfiguration.getUnidDataSource();
    if (StringUtils.isEmpty(dataSourceJndi)) {
        String errMsg = intres.getLocalizedMessage("ocsp.errornoinitparam", "unidDataSource");
        m_log.error(errMsg);
        throw new IllegalArgumentException(errMsg);
    }
    String trustDir = OcspConfiguration.getUnidTrustDir();
    if (StringUtils.isEmpty(trustDir)) {
        String errMsg = intres.getLocalizedMessage("ocsp.errornoinitparam", "unidTrustDir");
        m_log.error(errMsg);
        throw new IllegalArgumentException(errMsg);
    }
    // read all files from trustDir, expect that they are PEM formatted certificates
    CertTools.installBCProvider();
    File dir = new File(trustDir);
    try {
        if (dir == null || dir.isDirectory() == false) {
            m_log.error(dir.getCanonicalPath() + " is not a directory.");
            throw new IllegalArgumentException(dir.getCanonicalPath() + " is not a directory.");
        }
        File files[] = dir.listFiles();
        if (files == null || files.length == 0) {
            String errMsg = intres.getLocalizedMessage("ocsp.errornotrustfiles", dir.getCanonicalPath());
            m_log.error(errMsg);
        }
        for (int i = 0; i < files.length; i++) {
            final String fileName = files[i].getCanonicalPath();
            // Read the file, don't stop completely if one file has errors in it
            try {
                final byte bFromFile[] = FileTools.readFiletoBuffer(fileName);
                byte[] bytes;
                try {
                    bytes = FileTools.getBytesFromPEM(bFromFile, CertTools.BEGIN_CERTIFICATE,
                            CertTools.END_CERTIFICATE);
                } catch (Throwable t) {
                    bytes = bFromFile; // assume binary data (.der)
                }
                final X509Certificate cert = (X509Certificate) CertTools.getCertfromByteArray(bytes);
                this.trustedCerts.add(cert.getSerialNumber());
            } catch (CertificateException e) {
                String errMsg = intres.getLocalizedMessage("ocsp.errorreadingfile", fileName, "trustDir",
                        e.getMessage());
                m_log.error(errMsg, e);
            } catch (IOException e) {
                String errMsg = intres.getLocalizedMessage("ocsp.errorreadingfile", fileName, "trustDir",
                        e.getMessage());
                m_log.error(errMsg, e);
            }
        }
    } catch (IOException e) {
        String errMsg = intres.getLocalizedMessage("ocsp.errorreadingtrustfiles", e.getMessage());
        m_log.error(errMsg, e);
        throw new IllegalArgumentException(errMsg);
    }
    String cacertfile = OcspConfiguration.getUnidCaCert();
    if (StringUtils.isEmpty(cacertfile)) {
        String errMsg = intres.getLocalizedMessage("ocsp.errornoinitparam", "unidCACert");
        m_log.error(errMsg);
        throw new IllegalArgumentException(errMsg);
    }
    try {
        byte[] bytes = FileTools.getBytesFromPEM(FileTools.readFiletoBuffer(cacertfile),
                CertTools.BEGIN_CERTIFICATE, CertTools.END_CERTIFICATE);
        cacert = CertTools.getCertfromByteArray(bytes);
    } catch (Exception e) {
        String errMsg = intres.getLocalizedMessage("ocsp.errorreadingfile", "file", "cacertfile",
                e.getMessage());
        m_log.error(errMsg, e);
        throw new IllegalArgumentException(errMsg);
    }

}

From source file:be.fedict.eid.dss.protocol.simple.SimpleDSSProtocolService.java

public DSSRequest handleIncomingRequest(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    LOG.debug("handleIncomingRequest");
    String target = request.getParameter(TARGET_PARAMETER);
    if (null == target) {
        throw new IllegalArgumentException("missing target parameter");
    }/*w  w  w .j a  v  a 2s  .  co  m*/
    HttpSession httpSession = request.getSession();
    storeTarget(target, httpSession);

    String language = request.getParameter(LANGUAGE_PARAMETER);

    String relayState = request.getParameter(RELAY_STATE_PARAMETER);
    storeRelayState(relayState, httpSession);

    String signatureRequest = request.getParameter(SIGNATURE_REQUEST_PARAMETER);
    String signatureRequestId = request.getParameter(SIGNATURE_REQUEST_ID_PARAMETER);
    if (null == signatureRequest && null == signatureRequestId) {
        throw new IllegalArgumentException(
                "Need or " + SIGNATURE_REQUEST_PARAMETER + " or " + SIGNATURE_REQUEST_ID_PARAMETER);
    }

    byte[] decodedSignatureRequest = null;
    String contentType;
    if (null != signatureRequest) {
        /*
         * Needed during response for service signature.
         */
        storeSignatureRequest(signatureRequest, httpSession);
        decodedSignatureRequest = Base64.decodeBase64(signatureRequest);
        contentType = request.getParameter(CONTENT_TYPE_PARAMETER);
        LOG.debug("content type: " + contentType);
    } else {
        /*
         * Needed during response for service signature.
         */
        storeSignatureRequestId(signatureRequestId, httpSession);
        contentType = request.getParameter(CONTENT_TYPE_PARAMETER);
    }

    List<X509Certificate> serviceCertificateChain = null;
    String serviceSigned = request.getParameter(SERVICE_SIGNED_PARAMETER);
    if (null != serviceSigned) {

        // request service signature validation
        LOG.debug("ServiceSigned: " + serviceSigned);

        serviceCertificateChain = new LinkedList<X509Certificate>();
        String encodedServiceSignature = request.getParameter(SERVICE_SIGNATURE_PARAMETER);
        byte[] serviceSignatureValue = Base64.decodeBase64(encodedServiceSignature);

        /*
         * Parse the service certificate chain.
         */
        int serviceCertificateChainSize = Integer
                .parseInt(request.getParameter(SERVICE_CERTIFICATE_CHAIN_SIZE_PARAMETER));
        for (int idx = 1; idx <= serviceCertificateChainSize; idx++) {
            String encodedCertificate = request.getParameter(SERVICE_CERTIFICATE_PARAMETER_PREFIX + idx);
            byte[] certificateData = Base64.decodeBase64(encodedCertificate);
            X509Certificate certificate;
            try {
                certificate = (X509Certificate) this.certificateFactory
                        .generateCertificate(new ByteArrayInputStream(certificateData));
            } catch (CertificateException e) {
                throw new IllegalArgumentException("cert decoding error: " + e.getMessage());
            }
            serviceCertificateChain.add(certificate);

            // verify signature
            verifyServiceSignature(serviceSigned, target, signatureRequest, signatureRequestId, contentType,
                    language, relayState, serviceSignatureValue, serviceCertificateChain);

        }

    }

    if (null == contentType && null != signatureRequest) {
        contentType = "text/xml";
    }

    return new DSSRequest(decodedSignatureRequest, contentType, signatureRequestId, language, target,
            serviceCertificateChain);
}

From source file:be.fedict.trust.service.bean.DownloaderMDB.java

private void processColdStartMessage(ColdStartMessage coldStartMessage) {
    if (null == coldStartMessage) {
        return;/*w w w .  j av a  2  s.c  om*/
    }

    String crlUrl = coldStartMessage.getCrlUrl();
    String certUrl = coldStartMessage.getCertUrl();
    LOG.debug("cold start CRL URL: " + crlUrl);
    LOG.debug("cold start CA URL: " + certUrl);

    File crlFile = download(crlUrl);
    File certFile = download(certUrl);

    // parsing
    CertificateFactory certificateFactory;
    try {
        certificateFactory = CertificateFactory.getInstance("X.509");
    } catch (CertificateException e) {
        LOG.debug("certificate factory error: " + e.getMessage(), e);
        crlFile.delete();
        certFile.delete();
        return;
    }

    X509Certificate certificate = null;
    try {
        certificate = (X509Certificate) certificateFactory.generateCertificate(new FileInputStream(certFile));
    } catch (Exception e) {
        LOG.debug("error DER-parsing certificate");
        try {
            PEMReader pemReader = new PEMReader(new FileReader(certFile));
            certificate = (X509Certificate) pemReader.readObject();
            pemReader.close();
        } catch (Exception e2) {
            retry("error PEM-parsing certificate", e, certFile, crlFile);
        }
    }
    certFile.delete();

    X509CRL crl = null;
    try {
        crl = (X509CRL) certificateFactory.generateCRL(new FileInputStream(crlFile));
    } catch (Exception e) {
        retry("error parsing CRL", e, crlFile);
    }

    // first check whether the two correspond
    try {
        crl.verify(certificate.getPublicKey());
    } catch (Exception e) {
        LOG.error("no correspondence between CRL and CA");
        LOG.error("CRL issuer: " + crl.getIssuerX500Principal());
        LOG.debug("CA subject: " + certificate.getSubjectX500Principal());
        crlFile.delete();
        return;
    }
    LOG.debug("CRL matches CA: " + certificate.getSubjectX500Principal());

    // skip expired CAs
    Date now = new Date();
    Date notAfter = certificate.getNotAfter();
    if (now.after(notAfter)) {
        LOG.warn("CA already expired: " + certificate.getSubjectX500Principal());
        crlFile.delete();
        return;
    }

    // create database entitities
    CertificateAuthorityEntity certificateAuthority = this.certificateAuthorityDAO
            .findCertificateAuthority(certificate);
    if (null != certificateAuthority) {
        LOG.debug("CA already in cache: " + certificate.getSubjectX500Principal());
        crlFile.delete();
        return;
    }

    /*
     * Lookup Root CA's trust point via parent certificates' CA entity.
     */
    LOG.debug(
            "Lookup Root CA's trust point via parent certificates' CA entity - Don't have Issuer's Serial Number??");
    String parentIssuerName = certificate.getIssuerX500Principal().toString();
    CertificateAuthorityEntity parentCertificateAuthority = this.certificateAuthorityDAO
            .findCertificateAuthority(parentIssuerName);
    if (null == parentCertificateAuthority) {
        LOG.error("CA not found for " + parentIssuerName + " ?!");
        crlFile.delete();
        return;
    }
    LOG.debug("parent CA: " + parentCertificateAuthority.getName());
    TrustPointEntity parentTrustPoint = parentCertificateAuthority.getTrustPoint();
    if (null != parentTrustPoint) {
        LOG.debug("trust point parent: " + parentTrustPoint.getName());
        LOG.debug("previous trust point fire data: " + parentTrustPoint.getFireDate());
    } else {
        LOG.debug("no parent trust point");
    }

    // create new CA
    certificateAuthority = this.certificateAuthorityDAO.addCertificateAuthority(certificate, crlUrl);

    // prepare harvesting
    certificateAuthority.setTrustPoint(parentTrustPoint);
    certificateAuthority.setStatus(Status.PROCESSING);
    if (null != certificateAuthority.getTrustPoint()
            && null == certificateAuthority.getTrustPoint().getFireDate()) {
        try {
            this.schedulingService.startTimer(certificateAuthority.getTrustPoint());
        } catch (InvalidCronExpressionException e) {
            LOG.error("invalid cron expression");
            crlFile.delete();
            return;
        }
    }

    // notify harvester
    String crlFilePath = crlFile.getAbsolutePath();
    try {
        this.notificationService.notifyHarvester(certificate.getSubjectX500Principal().toString(), crlFilePath,
                false);
    } catch (JMSException e) {
        crlFile.delete();
        throw new RuntimeException(e);
    }
}