Example usage for javax.net.ssl SSLSession getPeerCertificates

List of usage examples for javax.net.ssl SSLSession getPeerCertificates

Introduction

In this page you can find the example usage for javax.net.ssl SSLSession getPeerCertificates.

Prototype

public java.security.cert.Certificate[] getPeerCertificates() throws SSLPeerUnverifiedException;

Source Link

Document

Returns the identity of the peer which was established as part of defining the session.

Usage

From source file:org.apache.tomcat.util.net.jsse.JSSE14Support.java

/** Return the X509certificates or null if we can't get them.
 *  XXX We should allow unverified certificates 
 *///  ww  w.ja  va 2s .c  o  m
protected X509Certificate[] getX509Certificates(SSLSession session) throws IOException {
    Certificate[] certs = null;
    try {
        certs = session.getPeerCertificates();
    } catch (Throwable t) {
        logger.debug("Error getting client certs", t);
        return null;
    }
    if (certs == null)
        return null;

    X509Certificate[] x509Certs = new X509Certificate[certs.length];
    for (int i = 0; i < certs.length; i++) {
        if (certs[i] instanceof X509Certificate) {
            // always currently true with the JSSE 1.1.x
            x509Certs[i] = (X509Certificate) certs[i];
        } else {
            try {
                byte[] buffer = certs[i].getEncoded();
                CertificateFactory cf = CertificateFactory.getInstance("X.509");
                ByteArrayInputStream stream = new ByteArrayInputStream(buffer);
                x509Certs[i] = (X509Certificate) cf.generateCertificate(stream);
            } catch (Exception ex) {
                logger.info("Error translating cert " + certs[i], ex);
                return null;
            }
        }
        if (logger.isTraceEnabled())
            logger.trace("Cert #" + i + " = " + x509Certs[i]);
    }
    if (x509Certs.length < 1)
        return null;
    return x509Certs;
}

From source file:org.jsslutils.extra.apachehttpclient.SslContextedSecureProtocolSocketFactory.java

/**
 * Describe <code>verifyHostname</code> method here.
 * //from   w  w w. j ava 2s.c  o  m
 * @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.
 * @exception UnknownHostException
 *                If we are not able to resolve the SSL sessions returned
 *                server host name.
 * @throws CertificateParsingException
 */
private void verifyHostname(SSLSocket socket) throws IOException, UnknownHostException {
    synchronized (this) {
        if (!verifyHostname)
            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 = (X509Certificate[]) session.getPeerCertificates();
    if (certs == null || certs.length == 0)
        throw new SSLPeerUnverifiedException("No server certificates found!");

    try {
        List<String> cns = new ArrayList<String>();
        boolean foundDnsSan = false;
        Collection<List<?>> subjectAltNames = certs[0].getSubjectAlternativeNames();
        if (subjectAltNames != null) {
            for (List<?> san : subjectAltNames) {
                if (((Integer) san.get(0)).intValue() == 2) {
                    foundDnsSan = true;
                    String sanDns = (String) san.get(1);
                    cns.add(sanDns);
                    if (hostname.equalsIgnoreCase(sanDns)) {
                        return;
                    }
                }
            }
        }
        if (!foundDnsSan) {
            // get the common names from the first cert
            X500Principal subjectDN = certs[0].getSubjectX500Principal();
            cns = getCNs(subjectDN);
            for (String cn : cns) {
                if (hostname.equalsIgnoreCase(cn)) {
                    return;
                }
            }
        }
        throw new SSLPeerUnverifiedException(
                "HTTPS hostname invalid: expected '" + hostname + "', received '" + cns + "'");
    } catch (CertificateParsingException e) {
        throw new IOException(e);
    }
}

From source file:org.lockss.protocol.BlockingStreamComm.java

protected void handshake(SSLSocket s) throws SSLPeerUnverifiedException {
    long oldTimeout = -2;
    try {/*  www.  j  a  v a2  s . c  o m*/
        oldTimeout = s.getSoTimeout();
        if (absTimeout(paramSslHandshakeTimeout) < absTimeout(oldTimeout)) {
            s.setSoTimeout((int) paramSslHandshakeTimeout);
        }
    } catch (SocketException e) {
        log.warning("Couldn't save/set socket timeout before handshake", e);
    }
    try {
        SSLSession session = s.getSession();
        java.security.cert.Certificate[] certs = session.getPeerCertificates();
        log.debug(session.getPeerHost() + " via " + session.getProtocol() + " verified");
    } catch (SSLPeerUnverifiedException ex) {
        log.error(s.getInetAddress() + ":" + s.getPort() + " not verified");
        try {
            s.close();
        } catch (IOException ex2) {
            log.error("Socket close threw " + ex2);
        }
        throw ex;
    } finally {
        if (!s.isClosed() && absTimeout(paramSslHandshakeTimeout) < absTimeout(oldTimeout)) {
            try {
                s.setSoTimeout((int) oldTimeout);
            } catch (SocketException e) {
                log.warning("Couldn't restore socket timeout after handshake", e);
            }
        }
    }
}

From source file:test.integ.be.fedict.commons.eid.client.SSLTest.java

@Test
public void testTestEIDBelgiumBe() throws Exception {
    Security.addProvider(new BeIDProvider());

    SSLContext sslContext = SSLContext.getInstance("TLS");
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("BeID");

    keyManagerFactory.init(null);//from  www.j a  v a 2 s .c o  m
    SecureRandom secureRandom = new SecureRandom();
    sslContext.init(keyManagerFactory.getKeyManagers(), new TrustManager[] { new ClientTestX509TrustManager() },
            secureRandom);
    SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
    SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket("test.eid.belgium.be", 443);
    LOG.debug("socket created");
    SSLSession sslSession = sslSocket.getSession();
    Certificate[] peerCertificates = sslSession.getPeerCertificates();
    for (Certificate peerCertificate : peerCertificates) {
        LOG.debug("peer certificate: " + ((X509Certificate) peerCertificate).getSubjectX500Principal());
    }
}

From source file:test.integ.be.fedict.trust.SSLTrustValidatorTest.java

@Test
public void testTestEIDBelgiumBe() throws Exception {
    Security.addProvider(new BeIDProvider());

    SSLContext sslContext = SSLContext.getInstance("TLS");
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("BeID");

    keyManagerFactory.init(null);//  www  . java2 s.  c  o m
    SecureRandom secureRandom = new SecureRandom();
    sslContext.init(keyManagerFactory.getKeyManagers(), new TrustManager[] { new ClientTestX509TrustManager() },
            secureRandom);
    SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
    SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket("test.eid.belgium.be", 443);
    LOG.debug("socket created");
    SSLSession sslSession = sslSocket.getSession();
    Certificate[] peerCertificates = sslSession.getPeerCertificates();
    for (Certificate peerCertificate : peerCertificates) {
        LOG.debug("peer certificate: " + ((X509Certificate) peerCertificate).getSubjectX500Principal());
    }

    MemoryCertificateRepository repository = new MemoryCertificateRepository();
    repository.addTrustPoint((X509Certificate) peerCertificates[peerCertificates.length - 1]);

    TrustValidator trustValidator = new TrustValidator(repository);
    TrustValidatorDecorator trustValidatorDecorator = new TrustValidatorDecorator();
    trustValidatorDecorator.addDefaultTrustLinkerConfig(trustValidator);
    trustValidator.isTrusted(peerCertificates);
}