Example usage for java.security.cert X509Certificate getIssuerDN

List of usage examples for java.security.cert X509Certificate getIssuerDN

Introduction

In this page you can find the example usage for java.security.cert X509Certificate getIssuerDN.

Prototype

public abstract Principal getIssuerDN();

Source Link

Document

Denigrated, replaced by #getIssuerX500Principal() .

Usage

From source file:org.apigw.authserver.web.controller.ApplicationManagementController.java

private Certificate createCertificate(MultipartFile certificate, BindingResult result) {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    Certificate cert = new Certificate();
    if (certificate != null && certificate.getSize() > 0) {

        try {//w w w.  j  a  v  a  2  s . co  m
            PEMReader r = new PEMReader(
                    new InputStreamReader(new ByteArrayInputStream(certificate.getBytes())));
            Object certObj = r.readObject();

            long reference = System.currentTimeMillis();

            // validate certificate
            if (certObj instanceof X509Certificate) {
                X509Certificate x509cert = (X509Certificate) certObj;
                BigInteger serialNumber = x509cert.getSerialNumber();

                String issuerDn = x509cert.getIssuerDN().getName();
                String subjectDn = x509cert.getSubjectDN().getName();

                cert.setCertificate(certificate.getBytes());
                cert.setSerialNumber(serialNumber.toString());
                cert.setIssuer(issuerDn);
                cert.setSubject(subjectDn);
                cert.setSubjectCommonName(extractFromDn(subjectDn, "CN"));
                cert.setSubjectOrganization(extractFromDn(subjectDn, "O"));
                cert.setSubjectOrganizationUnit(extractFromDn(subjectDn, "OU"));
                cert.setSubjectLocation(extractFromDn(subjectDn, "L"));
                cert.setSubjectCountry(extractFromDn(subjectDn, "C"));
                cert.setNotAfter(x509cert.getNotAfter());
                cert.setNotBefore(x509cert.getNotBefore());
            } else {
                String line;
                StringBuilder certString = new StringBuilder();
                while ((line = r.readLine()) != null) {
                    certString.append(line + "\n");
                }
                log.warn(
                        "Bad certificate [{}]: Provided certificate was of the wrong type: {}. Certificate: \n{}",
                        new Object[] { reference, certObj, certString.toString() });
                result.rejectValue("certificates", "invalid.certificate",
                        "Certifikatet r ej giltigt (Reference: " + reference + ")");
            }

            r.close();
        } catch (IOException e) {
            log.warn("Bad certificate");
            result.rejectValue("certificates", "invalid.certificate", "Certifikatet r ej giltigt ");
        }
    }
    return cert;
}

From source file:com.utest.webservice.client.rest.AuthSSLProtocolSocketFactory.java

@SuppressWarnings("unchecked")
private SSLContext createSSLContext() {
    try {//from   www . j a va  2  s. com
        KeyManager[] keymanagers = null;
        TrustManager[] trustmanagers = null;
        if (this.keystoreUrl != null) {
            KeyStore keystore = createKeyStore(this.keystoreUrl, this.keystorePassword);
            if (true) {
                Enumeration aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = (String) aliases.nextElement();
                    Certificate[] certs = keystore.getCertificateChain(alias);
                    if (certs != null) {
                        System.out.println("Certificate chain '" + alias + "':");
                        for (int c = 0; c < certs.length; c++) {
                            if (certs[c] instanceof X509Certificate) {
                                X509Certificate cert = (X509Certificate) certs[c];
                                System.out.println(" Certificate " + (c + 1) + ":");
                                System.out.println("  Subject DN: " + cert.getSubjectDN());
                                System.out.println("  Signature Algorithm: " + cert.getSigAlgName());
                                System.out.println("  Valid from: " + cert.getNotBefore());
                                System.out.println("  Valid until: " + cert.getNotAfter());
                                System.out.println("  Issuer: " + cert.getIssuerDN());
                            }
                        }
                    }
                }
            }
            keymanagers = createKeyManagers(keystore, this.keystorePassword);
        }
        if (this.truststoreUrl != null) {
            KeyStore keystore = createKeyStore(this.truststoreUrl, this.truststorePassword);
            if (true) {
                Enumeration aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = (String) aliases.nextElement();
                    System.out.println("Trusted certificate '" + alias + "':");
                    Certificate trustedcert = keystore.getCertificate(alias);
                    if (trustedcert != null && trustedcert instanceof X509Certificate) {
                        X509Certificate cert = (X509Certificate) trustedcert;
                        System.out.println("  Subject DN: " + cert.getSubjectDN());
                        System.out.println("  Signature Algorithm: " + cert.getSigAlgName());
                        System.out.println("  Valid from: " + cert.getNotBefore());
                        System.out.println("  Valid until: " + cert.getNotAfter());
                        System.out.println("  Issuer: " + cert.getIssuerDN());
                    }
                }
            }
            trustmanagers = createTrustManagers(keystore);
        }
        SSLContext sslcontext = SSLContext.getInstance("SSL");
        sslcontext.init(keymanagers, trustmanagers, null);
        return sslcontext;
    } catch (NoSuchAlgorithmException e) {
        System.out.println(e.getMessage());
        throw new AuthSSLInitializationError("Unsupported algorithm exception: " + e.getMessage());
    } catch (KeyStoreException e) {
        System.out.println(e.getMessage());
        throw new AuthSSLInitializationError("Keystore exception: " + e.getMessage());
    } catch (GeneralSecurityException e) {
        System.out.println(e.getMessage());
        throw new AuthSSLInitializationError("Key management exception: " + e.getMessage());
    } catch (IOException e) {
        System.out.println(e.getMessage());
        throw new AuthSSLInitializationError("I/O error reading keystore/truststore file: " + e.getMessage());
    }
}

From source file:org.apache.nifi.processors.standard.HandleHttpRequest.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    try {/*from ww  w . j a  v  a 2 s.co m*/
        if (!initialized.get()) {
            initializeServer(context);
        }
    } catch (Exception e) {
        context.yield();
        throw new ProcessException("Failed to initialize the server", e);
    }

    final HttpRequestContainer container = containerQueue.poll();
    if (container == null) {
        return;
    }

    final long start = System.nanoTime();
    final HttpServletRequest request = container.getRequest();
    FlowFile flowFile = session.create();
    try {
        flowFile = session.importFrom(request.getInputStream(), flowFile);
    } catch (final IOException e) {
        getLogger().error("Failed to receive content from HTTP Request from {} due to {}",
                new Object[] { request.getRemoteAddr(), e });
        session.remove(flowFile);
        return;
    }

    final String charset = request.getCharacterEncoding() == null
            ? context.getProperty(URL_CHARACTER_SET).getValue()
            : request.getCharacterEncoding();

    final String contextIdentifier = UUID.randomUUID().toString();
    final Map<String, String> attributes = new HashMap<>();
    try {
        putAttribute(attributes, HTTPUtils.HTTP_CONTEXT_ID, contextIdentifier);
        putAttribute(attributes, "mime.type", request.getContentType());
        putAttribute(attributes, "http.servlet.path", request.getServletPath());
        putAttribute(attributes, "http.context.path", request.getContextPath());
        putAttribute(attributes, "http.method", request.getMethod());
        putAttribute(attributes, "http.local.addr", request.getLocalAddr());
        putAttribute(attributes, HTTPUtils.HTTP_LOCAL_NAME, request.getLocalName());
        final String queryString = request.getQueryString();
        if (queryString != null) {
            putAttribute(attributes, "http.query.string", URLDecoder.decode(queryString, charset));
        }
        putAttribute(attributes, HTTPUtils.HTTP_REMOTE_HOST, request.getRemoteHost());
        putAttribute(attributes, "http.remote.addr", request.getRemoteAddr());
        putAttribute(attributes, "http.remote.user", request.getRemoteUser());
        putAttribute(attributes, HTTPUtils.HTTP_REQUEST_URI, request.getRequestURI());
        putAttribute(attributes, "http.request.url", request.getRequestURL().toString());
        putAttribute(attributes, "http.auth.type", request.getAuthType());

        putAttribute(attributes, "http.requested.session.id", request.getRequestedSessionId());
        final DispatcherType dispatcherType = request.getDispatcherType();
        if (dispatcherType != null) {
            putAttribute(attributes, "http.dispatcher.type", dispatcherType.name());
        }
        putAttribute(attributes, "http.character.encoding", request.getCharacterEncoding());
        putAttribute(attributes, "http.locale", request.getLocale());
        putAttribute(attributes, "http.server.name", request.getServerName());
        putAttribute(attributes, HTTPUtils.HTTP_PORT, request.getServerPort());

        final Enumeration<String> paramEnumeration = request.getParameterNames();
        while (paramEnumeration.hasMoreElements()) {
            final String paramName = paramEnumeration.nextElement();
            final String value = request.getParameter(paramName);
            attributes.put("http.param." + paramName, value);
        }

        final Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (final Cookie cookie : cookies) {
                final String name = cookie.getName();
                final String cookiePrefix = "http.cookie." + name + ".";
                attributes.put(cookiePrefix + "value", cookie.getValue());
                attributes.put(cookiePrefix + "domain", cookie.getDomain());
                attributes.put(cookiePrefix + "path", cookie.getPath());
                attributes.put(cookiePrefix + "max.age", String.valueOf(cookie.getMaxAge()));
                attributes.put(cookiePrefix + "version", String.valueOf(cookie.getVersion()));
                attributes.put(cookiePrefix + "secure", String.valueOf(cookie.getSecure()));
            }
        }

        if (queryString != null) {
            final String[] params = URL_QUERY_PARAM_DELIMITER.split(queryString);
            for (final String keyValueString : params) {
                final int indexOf = keyValueString.indexOf("=");
                if (indexOf < 0) {
                    // no =, then it's just a key with no value
                    attributes.put("http.query.param." + URLDecoder.decode(keyValueString, charset), "");
                } else {
                    final String key = keyValueString.substring(0, indexOf);
                    final String value;

                    if (indexOf == keyValueString.length() - 1) {
                        value = "";
                    } else {
                        value = keyValueString.substring(indexOf + 1);
                    }

                    attributes.put("http.query.param." + URLDecoder.decode(key, charset),
                            URLDecoder.decode(value, charset));
                }
            }
        }
    } catch (final UnsupportedEncodingException uee) {
        throw new ProcessException("Invalid character encoding", uee); // won't happen because charset has been validated
    }

    final Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        final String headerName = headerNames.nextElement();
        final String headerValue = request.getHeader(headerName);
        putAttribute(attributes, "http.headers." + headerName, headerValue);
    }

    final Principal principal = request.getUserPrincipal();
    if (principal != null) {
        putAttribute(attributes, "http.principal.name", principal.getName());
    }

    final X509Certificate certs[] = (X509Certificate[]) request
            .getAttribute("javax.servlet.request.X509Certificate");
    final String subjectDn;
    if (certs != null && certs.length > 0) {
        final X509Certificate cert = certs[0];
        subjectDn = cert.getSubjectDN().getName();
        final String issuerDn = cert.getIssuerDN().getName();

        putAttribute(attributes, HTTPUtils.HTTP_SSL_CERT, subjectDn);
        putAttribute(attributes, "http.issuer.dn", issuerDn);
    } else {
        subjectDn = null;
    }

    flowFile = session.putAllAttributes(flowFile, attributes);

    final HttpContextMap contextMap = context.getProperty(HTTP_CONTEXT_MAP)
            .asControllerService(HttpContextMap.class);
    final boolean registered = contextMap.register(contextIdentifier, request, container.getResponse(),
            container.getContext());

    if (!registered) {
        getLogger().warn(
                "Received request from {} but could not process it because too many requests are already outstanding; responding with SERVICE_UNAVAILABLE",
                new Object[] { request.getRemoteAddr() });

        try {
            container.getResponse().setStatus(Status.SERVICE_UNAVAILABLE.getStatusCode());
            container.getResponse().flushBuffer();
            container.getContext().complete();
        } catch (final Exception e) {
            getLogger().warn("Failed to respond with SERVICE_UNAVAILABLE message to {} due to {}",
                    new Object[] { request.getRemoteAddr(), e });
        }

        session.remove(flowFile);
        return;
    }

    final long receiveMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);
    session.getProvenanceReporter().receive(flowFile, HTTPUtils.getURI(attributes),
            "Received from " + request.getRemoteAddr() + (subjectDn == null ? "" : " with DN=" + subjectDn),
            receiveMillis);
    session.transfer(flowFile, REL_SUCCESS);
    getLogger().info("Transferring {} to 'success'; received from {}",
            new Object[] { flowFile, request.getRemoteAddr() });
}

From source file:org.sipfoundry.sipxconfig.admin.CertificateManagerImpl.java

private boolean isSystemGenerated(String fileName) {
    X509Certificate sslCrt = X509CertificateUtils
            .getX509Certificate(m_sslDirectory + File.separatorChar + SSL_CERT);
    X509Certificate currentCertificate = X509CertificateUtils
            .getX509Certificate(m_certdbDirectory + File.separatorChar + fileName);
    if (sslCrt != null && currentCertificate != null) {
        return StringUtils.equals(sslCrt.getIssuerDN().getName(), currentCertificate.getIssuerDN().getName());
    }//from w  w w  . jav a2  s.  c o  m
    return false;
}

From source file:org.apache.commons.httpclient.contrib.ssl.AuthSSLProtocolSocketFactory.java

private SSLContext createSSLContext() {
    try {/*from w w w.j a v a  2  s . co m*/
        KeyManager[] keymanagers = null;
        TrustManager[] trustmanagers = null;
        if (this.keystoreUrl != null) {
            KeyStore keystore = createKeyStore(this.keystoreUrl, this.keystorePassword);
            if (LOG.isDebugEnabled()) {
                Enumeration aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = (String) aliases.nextElement();
                    Certificate[] certs = keystore.getCertificateChain(alias);
                    if (certs != null) {
                        LOG.debug("Certificate chain '" + alias + "':");
                        for (int c = 0; c < certs.length; c++) {
                            if (certs[c] instanceof X509Certificate) {
                                X509Certificate cert = (X509Certificate) certs[c];
                                LOG.debug(" Certificate " + (c + 1) + ":");
                                LOG.debug("  Subject DN: " + cert.getSubjectDN());
                                LOG.debug("  Signature Algorithm: " + cert.getSigAlgName());
                                LOG.debug("  Valid from: " + cert.getNotBefore());
                                LOG.debug("  Valid until: " + cert.getNotAfter());
                                LOG.debug("  Issuer: " + cert.getIssuerDN());
                            }
                        }
                    }
                }
            }
            keymanagers = createKeyManagers(keystore, this.keystorePassword);
        }
        if (this.truststoreUrl != null) {
            KeyStore keystore = createKeyStore(this.truststoreUrl, this.truststorePassword);
            if (LOG.isDebugEnabled()) {
                Enumeration aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = (String) aliases.nextElement();
                    LOG.debug("Trusted certificate '" + alias + "':");
                    Certificate trustedcert = keystore.getCertificate(alias);
                    if (trustedcert != null && trustedcert instanceof X509Certificate) {
                        X509Certificate cert = (X509Certificate) trustedcert;
                        LOG.debug("  Subject DN: " + cert.getSubjectDN());
                        LOG.debug("  Signature Algorithm: " + cert.getSigAlgName());
                        LOG.debug("  Valid from: " + cert.getNotBefore());
                        LOG.debug("  Valid until: " + cert.getNotAfter());
                        LOG.debug("  Issuer: " + cert.getIssuerDN());
                    }
                }
            }
            trustmanagers = createTrustManagers(keystore);
        }
        SSLContext sslcontext = SSLContext.getInstance("SSL");
        sslcontext.init(keymanagers, trustmanagers, null);
        return sslcontext;
    } catch (NoSuchAlgorithmException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Unsupported algorithm exception: " + e.getMessage());
    } catch (KeyStoreException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Keystore exception: " + e.getMessage());
    } catch (GeneralSecurityException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Key management exception: " + e.getMessage());
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("I/O error reading keystore/truststore file: " + e.getMessage());
    }
}

From source file:se.inera.axel.shs.client.AuthSSLProtocolSocketFactory.java

private SSLContext createSSLContext() {
    try {//from  w ww.  j  av a 2s.  c  om
        KeyManager[] keymanagers = null;
        TrustManager[] trustmanagers = null;
        if (this.keystoreUrl != null) {
            KeyStore keystore = createKeyStore(this.keystoreUrl, this.keystorePassword);
            if (LOG.isDebugEnabled()) {
                Enumeration aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = (String) aliases.nextElement();
                    Certificate[] certs = keystore.getCertificateChain(alias);
                    if (certs != null) {
                        LOG.debug("Certificate chain '" + alias + "':");
                        for (int c = 0; c < certs.length; c++) {
                            if (certs[c] instanceof X509Certificate) {
                                X509Certificate cert = (X509Certificate) certs[c];
                                LOG.debug(" Certificate " + (c + 1) + ":");
                                LOG.debug("  Subject DN: " + cert.getSubjectDN());
                                LOG.debug("  Signature Algorithm: " + cert.getSigAlgName());
                                LOG.debug("  Valid from: " + cert.getNotBefore());
                                LOG.debug("  Valid until: " + cert.getNotAfter());
                                LOG.debug("  Issuer: " + cert.getIssuerDN());
                            }
                        }
                    }
                }
            }
            keymanagers = createKeyManagers(keystore, this.keystorePassword);
        }
        if (this.truststoreUrl != null) {
            KeyStore keystore = createKeyStore(this.truststoreUrl, this.truststorePassword);
            if (LOG.isDebugEnabled()) {
                Enumeration aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = (String) aliases.nextElement();
                    LOG.debug("Trusted certificate '" + alias + "':");
                    Certificate trustedcert = keystore.getCertificate(alias);
                    if (trustedcert != null && trustedcert instanceof X509Certificate) {
                        X509Certificate cert = (X509Certificate) trustedcert;
                        LOG.debug("  Subject DN: " + cert.getSubjectDN());
                        LOG.debug("  Signature Algorithm: " + cert.getSigAlgName());
                        LOG.debug("  Valid from: " + cert.getNotBefore());
                        LOG.debug("  Valid until: " + cert.getNotAfter());
                        LOG.debug("  Issuer: " + cert.getIssuerDN());
                    }
                }
            }
            trustmanagers = createTrustManagers(keystore);
        }
        SSLContext sslcontext = SSLContext.getInstance("TLSv1");
        sslcontext.init(keymanagers, trustmanagers, null);
        return sslcontext;
    } catch (NoSuchAlgorithmException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Unsupported algorithm exception: " + e.getMessage());
    } catch (KeyStoreException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Keystore exception: " + e.getMessage());
    } catch (GeneralSecurityException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Key management exception: " + e.getMessage());
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("I/O error reading keystore/truststore file: " + e.getMessage());
    }
}

From source file:org.tolven.config.model.CredentialManager.java

private X509Certificate[] getX509CertificateChain(CertificateGroupDetail certGroup) {
    List<X509Certificate> certificates = new ArrayList<X509Certificate>();
    X509Certificate certificate = getTolvenConfigWrapper().getX509Certificate(certGroup);
    certificates.add(certificate);//from w ww  . j  a  va2  s  .  c  o  m
    if (!certificate.getIssuerDN().equals(certificate.getSubjectDN())) {
        X509Certificate issuingCertificate = null;
        do {
            CertificateGroupDetail issuingCertGroup = getTolvenConfigWrapper()
                    .getCredentialGroup(certGroup.getCertificate().getCaRefId());
            issuingCertificate = getTolvenConfigWrapper().getX509Certificate(issuingCertGroup);
            if (!certificates.contains(issuingCertificate))
                certificates.add(issuingCertificate);

        } while ((!issuingCertificate.getIssuerDN().equals(issuingCertificate.getSubjectDN())));
    }
    X509Certificate[] certArr = new X509Certificate[certificates.size()];
    for (int i = 0; i < certificates.size(); i++)
        certArr[i] = certificates.get(i);
    return certArr;
}

From source file:com.app.mvc.http.ext.AuthSSLProtocolSocketFactory.java

private SSLContext createSSLContext() {
    try {/*  w  w w.j  ava2 s .c  o m*/
        KeyManager[] keymanagers = null;
        TrustManager[] trustmanagers = null;
        if (this.keystoreUrl != null) {
            KeyStore keystore = createKeyStore(this.keystoreUrl, this.keystorePassword);
            if (log.isDebugEnabled()) {
                Enumeration aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = (String) aliases.nextElement();
                    Certificate[] certs = keystore.getCertificateChain(alias);
                    if (certs != null) {
                        log.debug("Certificate chain '" + alias + "':");
                        for (int c = 0; c < certs.length; c++) {
                            if (certs[c] instanceof X509Certificate) {
                                X509Certificate cert = (X509Certificate) certs[c];
                                log.debug(" Certificate " + (c + 1) + ":");
                                log.debug("  Subject DN: " + cert.getSubjectDN());
                                log.debug("  Signature Algorithm: " + cert.getSigAlgName());
                                log.debug("  Valid from: " + cert.getNotBefore());
                                log.debug("  Valid until: " + cert.getNotAfter());
                                log.debug("  Issuer: " + cert.getIssuerDN());
                            }
                        }
                    }
                }
            }
            keymanagers = createKeyManagers(keystore, this.keystorePassword);
        }
        if (this.truststoreUrl != null) {
            KeyStore keystore = createKeyStore(this.truststoreUrl, this.truststorePassword);
            if (log.isDebugEnabled()) {
                Enumeration aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = (String) aliases.nextElement();
                    log.debug("Trusted certificate '" + alias + "':");
                    Certificate trustedcert = keystore.getCertificate(alias);
                    if (trustedcert != null && trustedcert instanceof X509Certificate) {
                        X509Certificate cert = (X509Certificate) trustedcert;
                        log.debug("  Subject DN: " + cert.getSubjectDN());
                        log.debug("  Signature Algorithm: " + cert.getSigAlgName());
                        log.debug("  Valid from: " + cert.getNotBefore());
                        log.debug("  Valid until: " + cert.getNotAfter());
                        log.debug("  Issuer: " + cert.getIssuerDN());
                    }
                }
            }
            trustmanagers = createTrustManagers(keystore);
        }
        SSLContext sslcontext = SSLContext.getInstance("SSL");
        sslcontext.init(keymanagers, trustmanagers, null);
        return sslcontext;
    } catch (NoSuchAlgorithmException e) {
        log.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Unsupported algorithm exception: " + e.getMessage());
    } catch (KeyStoreException e) {
        log.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Keystore exception: " + e.getMessage());
    } catch (GeneralSecurityException e) {
        log.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Key management exception: " + e.getMessage());
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("I/O error reading keystore/truststore file: " + e.getMessage());
    }
}

From source file:org.miloss.fgsms.bueller.AuthSSLProtocolSocketFactory.java

private SSLContext createSSLContext() {
    try {//w w w  .  j a va2s .com
        KeyManager[] keymanagers = null;
        TrustManager[] trustmanagers = null;
        if (this.keystoreUrl != null) {
            KeyStore keystore = createKeyStore(this.keystoreUrl, this.keystorePassword);
            if (LOG.isDebugEnabled()) {
                Enumeration aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = (String) aliases.nextElement();
                    Certificate[] certs = keystore.getCertificateChain(alias);
                    if (certs != null) {
                        LOG.debug("Certificate chain '" + alias + "':");
                        for (int c = 0; c < certs.length; c++) {
                            if (certs[c] instanceof X509Certificate) {
                                X509Certificate cert = (X509Certificate) certs[c];
                                LOG.debug(" Certificate " + (c + 1) + ":");
                                LOG.debug("  Subject DN: " + cert.getSubjectDN());
                                LOG.debug("  Signature Algorithm: " + cert.getSigAlgName());
                                LOG.debug("  Valid from: " + cert.getNotBefore());
                                LOG.debug("  Valid until: " + cert.getNotAfter());
                                LOG.debug("  Issuer: " + cert.getIssuerDN());
                            }
                        }
                    }
                }
            }
            keymanagers = createKeyManagers(keystore, this.keystorePassword);
        }
        if (this.truststoreUrl != null) {
            KeyStore keystore = createKeyStore(this.truststoreUrl, this.truststorePassword);
            if (LOG.isDebugEnabled()) {
                Enumeration aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = (String) aliases.nextElement();
                    LOG.debug("Trusted certificate '" + alias + "':");
                    Certificate trustedcert = keystore.getCertificate(alias);
                    if (trustedcert != null && trustedcert instanceof X509Certificate) {
                        X509Certificate cert = (X509Certificate) trustedcert;
                        LOG.debug("  Subject DN: " + cert.getSubjectDN());
                        LOG.debug("  Signature Algorithm: " + cert.getSigAlgName());
                        LOG.debug("  Valid from: " + cert.getNotBefore());
                        LOG.debug("  Valid until: " + cert.getNotAfter());
                        LOG.debug("  Issuer: " + cert.getIssuerDN());
                    }
                }
            }
            trustmanagers = createTrustManagers(keystore);
        }
        SSLContext sslcontext = SSLContext.getInstance("SSL");
        sslcontext.init(keymanagers, trustmanagers, null);
        return sslcontext;
    } catch (NoSuchAlgorithmException e) {
        LOG.error(e.getMessage(), e);
        // throw new AuthSSLInitializationError("Unsupported algorithm exception: " + e.getMessage());
    } catch (KeyStoreException e) {
        LOG.error(e.getMessage(), e);
        //  throw new AuthSSLInitializationError("Keystore exception: " + e.getMessage());
    } catch (GeneralSecurityException e) {
        LOG.error(e.getMessage(), e);
        // throw new AuthSSLInitializationError("Key management exception: " + e.getMessage());
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
        //   throw new AuthSSLInitializationError("I/O error reading keystore/truststore file: " + e.getMessage());
    }
    return null;
}

From source file:au.edu.monash.merc.capture.util.httpclient.ssl.AuthSSLProtocolSocketFactory.java

@SuppressWarnings("rawtypes")
private SSLContext createSSLContext() {
    try {//from ww  w. j av a 2 s. c o  m
        KeyManager[] keymanagers = null;
        TrustManager[] trustmanagers = null;
        if (this.keystoreUrl != null) {
            KeyStore keystore = createKeyStore(this.keystoreUrl, this.keystorePassword);
            if (LOG.isDebugEnabled()) {
                Enumeration aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = (String) aliases.nextElement();
                    Certificate[] certs = keystore.getCertificateChain(alias);
                    if (certs != null) {
                        LOG.debug("Certificate chain '" + alias + "':");
                        for (int c = 0; c < certs.length; c++) {
                            if (certs[c] instanceof X509Certificate) {
                                X509Certificate cert = (X509Certificate) certs[c];
                                LOG.debug(" Certificate " + (c + 1) + ":");
                                LOG.debug("  Subject DN: " + cert.getSubjectDN());
                                LOG.debug("  Signature Algorithm: " + cert.getSigAlgName());
                                LOG.debug("  Valid from: " + cert.getNotBefore());
                                LOG.debug("  Valid until: " + cert.getNotAfter());
                                LOG.debug("  Issuer: " + cert.getIssuerDN());
                            }
                        }
                    }
                }
            }
            keymanagers = createKeyManagers(keystore, this.keystorePassword);
        }
        if (this.truststoreUrl != null) {
            KeyStore keystore = createKeyStore(this.truststoreUrl, this.truststorePassword);
            if (LOG.isDebugEnabled()) {
                Enumeration aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = (String) aliases.nextElement();
                    LOG.debug("Trusted certificate '" + alias + "':");
                    Certificate trustedcert = keystore.getCertificate(alias);
                    if (trustedcert != null && trustedcert instanceof X509Certificate) {
                        X509Certificate cert = (X509Certificate) trustedcert;
                        LOG.debug("  Subject DN: " + cert.getSubjectDN());
                        LOG.debug("  Signature Algorithm: " + cert.getSigAlgName());
                        LOG.debug("  Valid from: " + cert.getNotBefore());
                        LOG.debug("  Valid until: " + cert.getNotAfter());
                        LOG.debug("  Issuer: " + cert.getIssuerDN());
                    }
                }
            }
            trustmanagers = createTrustManagers(keystore);
        }
        SSLContext sslcontext = SSLContext.getInstance("SSL");
        sslcontext.init(keymanagers, trustmanagers, null);
        return sslcontext;
    } catch (NoSuchAlgorithmException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Unsupported algorithm exception: " + e.getMessage());
    } catch (KeyStoreException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Keystore exception: " + e.getMessage());
    } catch (GeneralSecurityException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Key management exception: " + e.getMessage());
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("I/O error reading keystore/truststore file: " + e.getMessage());
    }
}