Example usage for java.security.cert X509Certificate getSubjectAlternativeNames

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

Introduction

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

Prototype

public Collection<List<?>> getSubjectAlternativeNames() throws CertificateParsingException 

Source Link

Document

Gets an immutable collection of subject alternative names from the SubjectAltName extension, (OID = 2.5.29.17).

Usage

From source file:com.vmware.o11n.plugin.crypto.service.CryptoCertificateService.java

/**
 *
 * @param cert/*from   w ww  .j a v  a2  s.c o m*/
 * @return
 * @throws CertificateParsingException
 */

public List<String> getSubjectAlternativeNames(X509Certificate cert) throws CertificateParsingException {
    ArrayList<String> toReturn = new ArrayList<>();
    Collection<List<?>> sans = cert.getSubjectAlternativeNames();
    if (sans != null) {
        if (log.isDebugEnabled()) {
            log.debug("Subject Alternative Names: " + sans.toString());
        }
        for (List<?> l : sans) {
            if (l.size() == 2) {
                Integer type = (Integer) l.get(0);
                if (type.equals(new Integer(2))) {
                    //DNS SAN
                    String value = (String) l.get(1);
                    toReturn.add("dns:" + value);
                } else {
                    String message = "SAN type '" + sanType.get(type) + "' not implemented";
                    log.warn(message);
                }
            } else {
                log.error("expected subject alternatives names object to have only 2 elements but " + l.size()
                        + " elements were present");
            }
        }
    } else if (log.isDebugEnabled()) {
        log.debug("Empty Subject Alternative Names");
    }
    return toReturn;
}

From source file:org.apache.http.HC4.conn.ssl.DefaultHostnameVerifier.java

private List<String> getSubjectAltNames(X509Certificate certificate, int type) {
    List<String> result = new ArrayList<String>();
    try {/* ww  w. java 2 s. c o m*/
        Collection<?> subjectAltNames = certificate.getSubjectAlternativeNames();
        if (subjectAltNames == null) {
            return Collections.emptyList();
        }
        for (Object subjectAltName : subjectAltNames) {
            List<?> entry = (List<?>) subjectAltName;
            if (entry == null || entry.size() < 2) {
                continue;
            }
            Integer altNameType = (Integer) entry.get(0);
            if (altNameType == null) {
                continue;
            }
            if (altNameType == type) {
                String altName = (String) entry.get(1);
                if (altName != null) {
                    result.add(altName);
                }
            }
        }
        return result;
    } catch (CertificateParsingException e) {
        return Collections.emptyList();
    }
}

From source file:edu.vt.middleware.ldap.ssl.DefaultHostnameVerifier.java

/**
 * Returns the subject alternative names matching the supplied name type from
 * the supplied certificate./*ww  w  . ja  v  a 2s  . com*/
 *
 * @param  cert  to get subject alt names from
 * @param  type  subject alt name type
 *
 * @return  subject alt names
 */
private String[] getSubjectAltNames(final X509Certificate cert, final SubjectAltNameType type) {
    final List<String> names = new ArrayList<String>();
    try {
        final Collection<List<?>> subjAltNames = cert.getSubjectAlternativeNames();
        if (subjAltNames != null) {
            for (List<?> generalName : subjAltNames) {
                final Integer nameType = (Integer) generalName.get(0);
                if (nameType.intValue() == type.ordinal()) {
                    names.add((String) generalName.get(1));
                }
            }
        }
    } catch (CertificateParsingException e) {
        if (this.logger.isWarnEnabled()) {
            this.logger.warn("Error reading subject alt names from certificate", e);
        }
    }
    return names.toArray(new String[names.size()]);
}

From source file:org.dcache.srm.client.FlexibleCredentialSSLConnectionSocketFactory.java

private void verifyHostname(final SSLSocket sslsock, final String hostname) throws IOException {
    try {//from   w ww  .  jav  a2s.c o m
        SSLSession session = sslsock.getSession();
        if (session == null) {
            // In our experience this only happens under IBM 1.4.x when
            // spurious (unrelated) certificates show up in the server'
            // chain.  Hopefully this will unearth the real problem:
            final InputStream in = sslsock.getInputStream();
            in.available();
            // If ssl.getInputStream().available() didn't cause an
            // exception, maybe at least now the session is available?
            session = sslsock.getSession();
            if (session == null) {
                // If it's still null, probably a startHandshake() will
                // unearth the real problem.
                sslsock.startHandshake();
                session = sslsock.getSession();
            }
        }
        if (session == null) {
            throw new SSLHandshakeException("SSL session not available");
        }

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Secure session established");
            LOGGER.debug(" negotiated protocol: {}", session.getProtocol());
            LOGGER.debug(" negotiated cipher suite: {}", session.getCipherSuite());

            try {

                final Certificate[] certs = session.getPeerCertificates();
                final X509Certificate x509 = (X509Certificate) certs[0];
                final X500Principal peer = x509.getSubjectX500Principal();

                LOGGER.debug(" peer principal: {}", peer);
                final Collection<List<?>> altNames1 = x509.getSubjectAlternativeNames();
                if (altNames1 != null) {
                    final List<String> altNames = new ArrayList<>();
                    for (final List<?> aC : altNames1) {
                        if (!aC.isEmpty()) {
                            altNames.add((String) aC.get(1));
                        }
                    }
                    LOGGER.debug(" peer alternative names: {}", altNames);
                }

                final X500Principal issuer = x509.getIssuerX500Principal();
                LOGGER.debug(" issuer principal: {}", issuer);
                final Collection<List<?>> altNames2 = x509.getIssuerAlternativeNames();
                if (altNames2 != null) {
                    final List<String> altNames = new ArrayList<>();
                    for (final List<?> aC : altNames2) {
                        if (!aC.isEmpty()) {
                            altNames.add((String) aC.get(1));
                        }
                    }
                    LOGGER.debug(" issuer alternative names: {}", altNames);
                }
            } catch (Exception ignore) {
            }
        }

        if (!this.hostnameVerifier.verify(hostname, session)) {
            final Certificate[] certs = session.getPeerCertificates();
            final X509Certificate x509 = (X509Certificate) certs[0];
            final X500Principal x500Principal = x509.getSubjectX500Principal();
            throw new SSLPeerUnverifiedException("Host name '" + hostname + "' does not match "
                    + "the certificate subject provided by the peer (" + x500Principal.toString() + ")");
        }
        // verifyHostName() didn't blowup - good!
    } catch (RuntimeException | IOException iox) {
        // close the socket before re-throwing the exception
        try {
            sslsock.close();
        } catch (final Exception x) {
            iox.addSuppressed(x);
        }
        throw iox;
    }
}

From source file:com.amazon.speech.speechlet.authentication.SpeechletRequestSignatureVerifier.java

/**
 * Retrieves the certificate from the specified URL and confirms that the certificate is valid.
 *
 * @param signingCertificateChainUrl/*from  ww  w.j  a v  a 2  s.c  om*/
 *            the URL to retrieve the certificate chain from
 * @return the certificate at the specified URL, if the certificate is valid
 * @throws CertificateException
 *             if the certificate cannot be retrieve or is invalid
 */
public static X509Certificate retrieveAndVerifyCertificateChain(final String signingCertificateChainUrl)
        throws CertificateException {
    try (InputStream in = getAndVerifySigningCertificateChainUrl(signingCertificateChainUrl).openStream()) {
        CertificateFactory certificateFactory = CertificateFactory.getInstance(Sdk.SIGNATURE_CERTIFICATE_TYPE);
        @SuppressWarnings("unchecked")
        Collection<X509Certificate> certificateChain = (Collection<X509Certificate>) certificateFactory
                .generateCertificates(in);
        /*
         * check the before/after dates on the certificate date to confirm that it is valid on
         * the current date
         */
        X509Certificate signingCertificate = certificateChain.iterator().next();
        signingCertificate.checkValidity();

        // check the certificate chain
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init((KeyStore) null);

        X509TrustManager x509TrustManager = null;
        for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) {
            if (trustManager instanceof X509TrustManager) {
                x509TrustManager = (X509TrustManager) trustManager;
            }
        }

        if (x509TrustManager == null) {
            throw new IllegalStateException(
                    "No X509 TrustManager available. Unable to check certificate chain");
        } else {
            x509TrustManager.checkServerTrusted(
                    certificateChain.toArray(new X509Certificate[certificateChain.size()]),
                    Sdk.SIGNATURE_KEY_TYPE);
        }

        /*
         * verify Echo API's hostname is specified as one of subject alternative names on the
         * signing certificate
         */
        if (!subjectAlernativeNameListContainsEchoSdkDomainName(
                signingCertificate.getSubjectAlternativeNames())) {
            throw new CertificateException("The provided certificate is not valid for the Echo SDK");
        }

        return signingCertificate;
    } catch (KeyStoreException | IOException | NoSuchAlgorithmException ex) {
        throw new CertificateException("Unable to verify certificate at URL: " + signingCertificateChainUrl,
                ex);
    }
}

From source file:com.serphacker.serposcope.scraper.http.extensions.ScrapClientSSLConnectionFactory.java

private void verifyHostname(final SSLSocket sslsock, final String hostname) throws IOException {
    try {/*from  w  ww  .  j a  va 2  s .co  m*/
        SSLSession session = sslsock.getSession();
        if (session == null) {
            // In our experience this only happens under IBM 1.4.x when
            // spurious (unrelated) certificates show up in the server'
            // chain.  Hopefully this will unearth the real problem:
            final InputStream in = sslsock.getInputStream();
            in.available();
            // If ssl.getInputStream().available() didn't cause an
            // exception, maybe at least now the session is available?
            session = sslsock.getSession();
            if (session == null) {
                // If it's still null, probably a startHandshake() will
                // unearth the real problem.
                sslsock.startHandshake();
                session = sslsock.getSession();
            }
        }
        if (session == null) {
            throw new SSLHandshakeException("SSL session not available");
        }

        if (this.log.isDebugEnabled()) {
            this.log.debug("Secure session established");
            this.log.debug(" negotiated protocol: " + session.getProtocol());
            this.log.debug(" negotiated cipher suite: " + session.getCipherSuite());

            try {

                final Certificate[] certs = session.getPeerCertificates();
                final X509Certificate x509 = (X509Certificate) certs[0];
                final X500Principal peer = x509.getSubjectX500Principal();

                this.log.debug(" peer principal: " + peer.toString());
                final Collection<List<?>> altNames1 = x509.getSubjectAlternativeNames();
                if (altNames1 != null) {
                    final List<String> altNames = new ArrayList<String>();
                    for (final List<?> aC : altNames1) {
                        if (!aC.isEmpty()) {
                            altNames.add((String) aC.get(1));
                        }
                    }
                    this.log.debug(" peer alternative names: " + altNames);
                }

                final X500Principal issuer = x509.getIssuerX500Principal();
                this.log.debug(" issuer principal: " + issuer.toString());
                final Collection<List<?>> altNames2 = x509.getIssuerAlternativeNames();
                if (altNames2 != null) {
                    final List<String> altNames = new ArrayList<String>();
                    for (final List<?> aC : altNames2) {
                        if (!aC.isEmpty()) {
                            altNames.add((String) aC.get(1));
                        }
                    }
                    this.log.debug(" issuer alternative names: " + altNames);
                }
            } catch (Exception ignore) {
            }
        }

        HostnameVerifier hostnameVerifier = insecure ? insecureHostnameVerifier : defaultHostnameVerifier;
        if (!hostnameVerifier.verify(hostname, session)) {
            final Certificate[] certs = session.getPeerCertificates();
            final X509Certificate x509 = (X509Certificate) certs[0];
            final X500Principal x500Principal = x509.getSubjectX500Principal();
            throw new SSLPeerUnverifiedException("Host name '" + hostname + "' does not match "
                    + "the certificate subject provided by the peer (" + x500Principal.toString() + ")");
        }
        // verifyHostName() didn't blowup - good!
    } catch (final IOException iox) {
        // close the socket before re-throwing the exception
        try {
            sslsock.close();
        } catch (final Exception x) {
            /*ignore*/ }
        throw iox;
    }
}

From source file:com.predic8.membrane.core.transport.ssl.SSLContext.java

public SSLContext(SSLParser sslParser, ResolverMap resourceResolver, String baseLocation) {
    this.sslParser = sslParser;
    try {//  w  w w  . j a va  2  s .c  o m
        String algorihm = KeyManagerFactory.getDefaultAlgorithm();
        if (sslParser.getAlgorithm() != null)
            algorihm = sslParser.getAlgorithm();

        KeyManagerFactory kmf = null;
        String keyStoreType = "JKS";
        if (sslParser.getKeyStore() != null) {
            if (sslParser.getKeyStore().getKeyAlias() != null)
                throw new InvalidParameterException("keyAlias is not yet supported.");
            char[] keyPass = "changeit".toCharArray();
            if (sslParser.getKeyStore().getKeyPassword() != null)
                keyPass = sslParser.getKeyStore().getKeyPassword().toCharArray();

            if (sslParser.getKeyStore().getType() != null)
                keyStoreType = sslParser.getKeyStore().getType();
            KeyStore ks = openKeyStore(sslParser.getKeyStore(), "JKS", keyPass, resourceResolver, baseLocation);
            kmf = KeyManagerFactory.getInstance(algorihm);
            kmf.init(ks, keyPass);

            Enumeration<String> aliases = ks.aliases();
            while (aliases.hasMoreElements()) {
                String alias = aliases.nextElement();
                if (ks.isKeyEntry(alias)) {
                    // first key is used by the KeyManagerFactory
                    Certificate c = ks.getCertificate(alias);
                    if (c instanceof X509Certificate) {
                        X509Certificate x = (X509Certificate) c;

                        dnsNames = new ArrayList<String>();

                        Collection<List<?>> subjectAlternativeNames = x.getSubjectAlternativeNames();
                        if (subjectAlternativeNames != null)
                            for (List<?> l : subjectAlternativeNames) {
                                if (l.get(0) instanceof Integer && ((Integer) l.get(0) == 2))
                                    dnsNames.add(l.get(1).toString());
                            }
                    }
                    break;
                }
            }

        }
        TrustManagerFactory tmf = null;
        if (sslParser.getTrustStore() != null) {
            String trustAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
            if (sslParser.getTrustStore().getAlgorithm() != null)
                trustAlgorithm = sslParser.getTrustStore().getAlgorithm();
            KeyStore ks = openKeyStore(sslParser.getTrustStore(), keyStoreType, null, resourceResolver,
                    baseLocation);
            tmf = TrustManagerFactory.getInstance(trustAlgorithm);
            tmf.init(ks);
        }

        TrustManager[] tms = tmf != null ? tmf.getTrustManagers()
                : null /* trust anyone: new TrustManager[] { new NullTrustManager() } */;
        if (sslParser.isIgnoreTimestampCheckFailure())
            tms = new TrustManager[] { new TrustManagerWrapper(tms, true) };

        if (sslParser.getProtocol() != null)
            sslc = javax.net.ssl.SSLContext.getInstance(sslParser.getProtocol());
        else
            sslc = javax.net.ssl.SSLContext.getInstance("TLS");

        sslc.init(kmf != null ? kmf.getKeyManagers() : null, tms, null);

        if (sslParser.getCiphers() != null) {
            ciphers = sslParser.getCiphers().split(",");
            Set<String> supportedCiphers = Sets.newHashSet(sslc.getSocketFactory().getSupportedCipherSuites());
            for (String cipher : ciphers) {
                if (!supportedCiphers.contains(cipher))
                    throw new InvalidParameterException("Unknown cipher " + cipher);
                if (cipher.contains("_RC4_"))
                    log.warn("Cipher " + cipher + " uses RC4, which is deprecated.");
            }
        } else {
            // use all default ciphers except those using RC4
            String supportedCiphers[] = sslc.getSocketFactory().getDefaultCipherSuites();
            ArrayList<String> ciphers = new ArrayList<String>(supportedCiphers.length);
            for (String cipher : supportedCiphers)
                if (!cipher.contains("_RC4_"))
                    ciphers.add(cipher);
            sortCiphers(ciphers);
            this.ciphers = ciphers.toArray(new String[ciphers.size()]);
        }
        if (setUseCipherSuitesOrderMethod == null)
            log.warn(
                    "Cannot set the cipher suite order before Java 8. This prevents Forward Secrecy with some SSL clients.");

        if (sslParser.getProtocols() != null) {
            protocols = sslParser.getProtocols().split(",");
        } else {
            protocols = null;
        }

        if (sslParser.getClientAuth() == null) {
            needClientAuth = false;
            wantClientAuth = false;
        } else if (sslParser.getClientAuth().equals("need")) {
            needClientAuth = true;
            wantClientAuth = true;
        } else if (sslParser.getClientAuth().equals("want")) {
            needClientAuth = false;
            wantClientAuth = true;
        } else {
            throw new RuntimeException("Invalid value '" + sslParser.getClientAuth()
                    + "' in clientAuth: expected 'want', 'need' or not set.");
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.vmware.identity.idm.server.clientcert.IdmClientCertificateValidator.java

/**
 * validate the subject represent in the given client certificate. The
 * process uses following information in this order: 1. UPN in SAN,KeyStore
 * 2. Subject DN 3. Other alternative names in the SAN if enabled
 *
 * @param data//from   w w w  . j av  a 2  s.  co  m
 *            DER encoded data
 * @return String UPN of the subject that the cert was issued to or throw
 *         exception.
 * @throws IdmClientCertificateParsingException
 *             Not able to extract UPN from the certificate.
 */

public String extractUPN(X509Certificate clientCert)
        throws IdmClientCertificateParsingException, InvalidPrincipalException, IDMException {

    String upn = null;
    /**
     * UPN matching
     */
    logger.info("Extract and validating subject in client certificate");

    Collection<List<?>> altNames;
    try {
        altNames = clientCert.getSubjectAlternativeNames();
    } catch (CertificateParsingException e) {
        logger.error("No subject alternative name found in the cert.");
        throw new IdmClientCertificateParsingException("Error in finding cert SAN", e);
    }

    if (altNames == null) {
        logger.error("No subject alternative name found in the cert.");
        throw new IdmClientCertificateParsingException("Empty Subject Alternative Names");
    }

    // Examine each SAN entry for UPN that map to a registered principal
    for (List<?> altName : altNames) {
        Validate.isTrue(altName.size() > 1, "Invalid certicate SAN entry");
        Object altNameVal = altName.get(1);
        /*
         * Step 1. Get candidate UPN string
         * Expect UPN defined as "OtherName" type of SAN. Only upn will be returned as a byte
         * array.
         */
        if (Integer.valueOf(IdmClientCertificateValidator.SUBALTNAME_TYPE_OTHERNAME).equals(altName.get(0))
                && altNameVal instanceof byte[]) {

            byte[] altNameValByte = (byte[]) altNameVal;

            try {
                upn = parseDERString(altNameValByte);
            } catch (Throwable t) {
                throw new IdmClientCertificateParsingException(
                        "Failed to parse SAN entry with \'OtherName\' type.", t);
            }
        } else {
            /*
             * Unknown type. we are not parsing this SAN entry
             */
            String skippedAltName = null;
            if (altNameVal instanceof String) {
                skippedAltName = (String) altNameVal;
            } else if (altNameVal instanceof byte[]) {
                skippedAltName = new String((byte[]) altNameVal);
            }
            logger.debug("Skipping SAN entry of type " + altName.get(0) + " with value: " + skippedAltName);
        }

        if (upn != null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Successfully extracted UPN from SAN entry:" + upn);
            }
            break;
        }
    }

    /*
     * if no UPN found in SAN. Next, TBD: should we try the Subject DN's
     * X500Principal Note: if UPN is found in SAN but matching to user
     * failed, we do not look farther.
     */
    if (upn == null) {
        throw new IdmClientCertificateParsingException("No UPN entry in Subject Alternative Names extension");
    }

    return upn;
}

From source file:org.security4java.X509SubjectAlternativeNameRetriever.java

@SuppressWarnings({ "rawtypes" })
public String getUserName(X509Certificate clientCert) {
    if (logger.isDebugEnabled()) {
        logger.debug("getUserName(X509Certificate) - start");
    }//w w  w .  j a va  2  s.com

    String userName = null;
    if (clientCert != null) {
        boolean foundUserName = false;
        if (alternativeNameTypeValue != NOT_EXISTING_TYPE) {
            try {
                if (clientCert.getSubjectAlternativeNames() != null) {
                    Collection subjectAlternativeNames = clientCert.getSubjectAlternativeNames();
                    Iterator iter = subjectAlternativeNames.iterator();
                    /* 
                     * The method goes over collection of Subject Alternative Names.
                     * If the Subject Alternative Name type is equal to the configured
                     * predefined identity name, return the user name. 
                     */
                    while (iter.hasNext()) {
                        List subjectAlternativeName = (List) iter.next();
                        Integer type = (Integer) subjectAlternativeName.get(0);
                        if (type.intValue() == alternativeNameTypeValue) {
                            Object subjectAlternativeNameValue = subjectAlternativeName.get(1);
                            if (subjectAlternativeNameValue instanceof String) {
                                userName = (String) subjectAlternativeNameValue;
                                foundUserName = true;
                                break;
                            } else if (subjectAlternativeNameValue instanceof byte[]) {
                                byte[] subjectAlternativeNameValueBytes = (byte[]) subjectAlternativeNameValue;
                                userName = getStringFromASNDerEncodedByteArray(
                                        subjectAlternativeNameValueBytes);
                                if (userName != null) {
                                    foundUserName = true;
                                    break;
                                }
                            } else {
                                if (logger.isInfoEnabled()) {
                                    logger.info(
                                            "Can not get UserName, the subjectAlternativeName not supported ["
                                                    + subjectAlternativeNameValue + "].");
                                }
                            }
                        }
                    }
                }
            } catch (CertificateParsingException e) {
                logger.info("Can not get UserName, can not get subjectAlternativeNames from certificate ["
                        + e.getMessage() + "].");
            }

        } else {
            if (logger.isDebugEnabled()) {
                logger.debug("Can not get UserName, generalName is null");
            }
        }
        if (!foundUserName) {
            logger.info("Can not found userName as part of subjectAlternativeName ["
                    + alternativeNameConfiguration + "]. Return the whole subject.");
            userName = getSubjectDN(clientCert);
        }

    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("Can not get UserName, clientCert is null");
        }
    }
    if (logger.isDebugEnabled()) {
        logger.debug("getUserName(X509Certificate) - end; Ret is [" + userName + "].");
    }

    return userName;
}

From source file:com.newrelic.agent.deps.org.apache.http.conn.ssl.SSLConnectionSocketFactory.java

private void verifyHostname(final SSLSocket sslsock, final String hostname) throws IOException {
    try {//from   w  ww .  j ava  2 s  .c om
        SSLSession session = sslsock.getSession();
        if (session == null) {
            // In our experience this only happens under IBM 1.4.x when
            // spurious (unrelated) certificates show up in the server'
            // chain.  Hopefully this will unearth the real problem:
            final InputStream in = sslsock.getInputStream();
            in.available();
            // If ssl.getInputStream().available() didn't cause an
            // exception, maybe at least now the session is available?
            session = sslsock.getSession();
            if (session == null) {
                // If it's still null, probably a startHandshake() will
                // unearth the real problem.
                sslsock.startHandshake();
                session = sslsock.getSession();
            }
        }
        if (session == null) {
            throw new SSLHandshakeException("SSL session not available");
        }

        if (this.log.isDebugEnabled()) {
            this.log.debug("Secure session established");
            this.log.debug(" negotiated protocol: " + session.getProtocol());
            this.log.debug(" negotiated cipher suite: " + session.getCipherSuite());

            try {

                final Certificate[] certs = session.getPeerCertificates();
                final X509Certificate x509 = (X509Certificate) certs[0];
                final X500Principal peer = x509.getSubjectX500Principal();

                this.log.debug(" peer principal: " + peer.toString());
                final Collection<List<?>> altNames1 = x509.getSubjectAlternativeNames();
                if (altNames1 != null) {
                    final List<String> altNames = new ArrayList<String>();
                    for (final List<?> aC : altNames1) {
                        if (!aC.isEmpty()) {
                            altNames.add((String) aC.get(1));
                        }
                    }
                    this.log.debug(" peer alternative names: " + altNames);
                }

                final X500Principal issuer = x509.getIssuerX500Principal();
                this.log.debug(" issuer principal: " + issuer.toString());
                final Collection<List<?>> altNames2 = x509.getIssuerAlternativeNames();
                if (altNames2 != null) {
                    final List<String> altNames = new ArrayList<String>();
                    for (final List<?> aC : altNames2) {
                        if (!aC.isEmpty()) {
                            altNames.add((String) aC.get(1));
                        }
                    }
                    this.log.debug(" issuer alternative names: " + altNames);
                }
            } catch (Exception ignore) {
            }
        }

        if (!this.hostnameVerifier.verify(hostname, session)) {
            final Certificate[] certs = session.getPeerCertificates();
            final X509Certificate x509 = (X509Certificate) certs[0];
            final X500Principal x500Principal = x509.getSubjectX500Principal();
            throw new SSLPeerUnverifiedException("Host name '" + hostname + "' does not match "
                    + "the certificate subject provided by the peer (" + x500Principal.toString() + ")");
        }
        // verifyHostName() didn't blowup - good!
    } catch (final IOException iox) {
        // close the socket before re-throwing the exception
        try {
            sslsock.close();
        } catch (final Exception x) {
            /*ignore*/ }
        throw iox;
    }
}