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:MainClass.java

public static void main(String args[]) throws Exception {
    System.setProperty("javax.net.ssl.trustStore", "clienttrust");

    SSLSocketFactory ssf = (SSLSocketFactory) SSLSocketFactory.getDefault();
    Socket s = ssf.createSocket("127.0.0.1", 5432);

    SSLSession session = ((SSLSocket) s).getSession();
    Certificate[] cchain = session.getPeerCertificates();
    System.out.println("The Certificates used by peer");
    for (int i = 0; i < cchain.length; i++) {
        System.out.println(((X509Certificate) cchain[i]).getSubjectDN());
    }/*  w  w w  . java  2  s . co  m*/
    System.out.println("Peer host is " + session.getPeerHost());
    System.out.println("Cipher is " + session.getCipherSuite());
    System.out.println("Protocol is " + session.getProtocol());
    System.out.println("ID is " + new BigInteger(session.getId()));
    System.out.println("Session created in " + session.getCreationTime());
    System.out.println("Session accessed in " + session.getLastAccessedTime());

    BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
    String x = in.readLine();
    System.out.println(x);
    in.close();

}

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    SSLSocketFactory factory = HttpsURLConnection.getDefaultSSLSocketFactory();
    SSLSocket socket = (SSLSocket) factory.createSocket("127.0.0.1", 9999);
    socket.startHandshake();/*from  w w  w. ja  v a 2  s  .co m*/
    SSLSession session = socket.getSession();
    java.security.cert.Certificate[] servercerts = session.getPeerCertificates();

    List mylist = new ArrayList();
    for (int i = 0; i < servercerts.length; i++) {
        mylist.add(servercerts[i]);
    }

    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    CertPath cp = cf.generateCertPath(mylist);

    FileOutputStream f = new FileOutputStream("CertPath.dat");
    ObjectOutputStream b = new ObjectOutputStream(f);
    b.writeObject(cp);

}

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    SSLServerSocketFactory ssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
    SSLServerSocket ss = (SSLServerSocket) ssf.createServerSocket(443);
    ss.setNeedClientAuth(true);/* w  ww .  j ava  2s .  c o m*/
    while (true) {
        Socket s = ss.accept();

        SSLSession session = ((SSLSocket) s).getSession();
        Certificate[] cchain = session.getPeerCertificates();
        for (int j = 0; j < cchain.length; j++) {
            System.out.println(((X509Certificate) cchain[j]).getSubjectDN());
        }
        PrintStream out = new PrintStream(s.getOutputStream());
        BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
        String info = null;
        while ((info = in.readLine()) != null) {
            System.out.println("now got " + info);
            if (info.equals(""))
                break;
        }

        out.println("HTTP/1.0 200 OK\nMIME_version:1.0");
        out.println("Content_Type:text/html");
        String c = "<html> <head></head><body> <h1> Hi,</h1></Body></html>";
        out.println("Content_Length:" + c.length());
        out.println("");
        out.println(c);
        out.close();
        s.close();
        in.close();
    }
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();

    String hostName = "hostName";
    String fileName = "fileName";

    SSLSocket sslsock = (SSLSocket) factory.createSocket(hostName, 443);

    SSLSession session = sslsock.getSession();
    X509Certificate cert;/*from   w w w.  j  a  v a 2s .  c  o m*/
    try {
        cert = (X509Certificate) session.getPeerCertificates()[0];
    } catch (SSLPeerUnverifiedException e) {
        System.err.println(session.getPeerHost() + " did not present a valid certificate.");
        return;
    }

    System.out.println(session.getPeerHost() + " has presented a certificate belonging to:");
    Principal p = cert.getSubjectDN();
    System.out.println("\t[" + p.getName() + "]");
    System.out.println("The certificate bears the valid signature of:");
    System.out.println("\t[" + cert.getIssuerDN().getName() + "]");

    System.out.print("Do you trust this certificate (y/n)? ");
    System.out.flush();
    BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
    if (Character.toLowerCase(console.readLine().charAt(0)) != 'y')
        return;

    PrintWriter out = new PrintWriter(sslsock.getOutputStream());

    out.print("GET " + fileName + " HTTP/1.0\r\n\r\n");
    out.flush();

    BufferedReader in = new BufferedReader(new InputStreamReader(sslsock.getInputStream()));
    String line;
    while ((line = in.readLine()) != null)
        System.out.println(line);

    sslsock.close();
}

From source file:Main.java

/**
 * Returns the X509Certificate for the server this session is connected to. The certificate may be null.
 *
 * @param sslSession SSL session connected to upstream server
 * @return the X.509 certificate from the upstream server, or null if no certificate is available
 *//*from w ww .  j a  va  2  s  . com*/
public static X509Certificate getServerCertificate(SSLSession sslSession) {
    Certificate[] peerCertificates;
    try {
        peerCertificates = sslSession.getPeerCertificates();
    } catch (SSLPeerUnverifiedException e) {
        peerCertificates = null;
    }

    if (peerCertificates != null && peerCertificates.length > 0) {
        Certificate peerCertificate = peerCertificates[0];
        if (peerCertificate != null && peerCertificate instanceof X509Certificate) {
            return (X509Certificate) peerCertificates[0];
        }
    }

    // no X.509 certificate was found for this server
    return null;
}

From source file:org.aevans.goat.net.SSLStrategyGetter.java

public static SchemeIOSessionStrategy getSchemeIOSessionStrategy() {
    DefaultHostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(
            PublicSuffixMatcherLoader.getDefault());
    SchemeIOSessionStrategy sioss = new SchemeIOSessionStrategy() {

        @Override// www  . ja v  a 2s.c o  m
        public boolean isLayeringRequired() {
            return true;
        }

        @Override
        public IOSession upgrade(final HttpHost host, final IOSession iosession) throws IOException {

            SSLSetupHandler handler = new SSLSetupHandler() {

                @Override
                public void initalize(SSLEngine sslengine) throws SSLException {
                }

                @Override
                public void verify(IOSession iosession, SSLSession sslsession) throws SSLException {
                    if (!hostnameVerifier.verify(host.getHostName(), sslsession)) {
                        final java.security.cert.Certificate[] certs = sslsession.getPeerCertificates();
                        final X509Certificate x509 = (X509Certificate) certs[0];
                        final X500Principal x500Principal = x509.getSubjectX500Principal();
                        throw new SSLPeerUnverifiedException("Host name '" + host.getHostName()
                                + "' does not match " + "the certificate subject provided by the peer ("
                                + x500Principal.toString() + ")");
                    }
                }

            };
            SSLBufferManagementStrategy sslbm = new ReleasableSSLBufferManagementStrategy();
            SSLIOSession ssio = new SSLIOSession(iosession, SSLMode.CLIENT, host, SSLContexts.createDefault(),
                    handler, sslbm);
            iosession.setAttribute(SSLIOSession.SESSION_KEY, ssio);
            ssio.initialize();
            return ssio;
        }

    };

    return sioss;
}

From source file:ee.ria.xroad.proxy.clientproxy.AuthTrustVerifier.java

private static X509Certificate[] getPeerCertificates(SSLSession session) {
    if (session == null) {
        throw new CodedException(X_SSL_AUTH_FAILED, "No TLS session");
    }/*  w ww  . j  a  v a  2 s.  c  om*/

    try {
        // Note: assuming X509-based auth
        return (X509Certificate[]) session.getPeerCertificates();
    } catch (SSLPeerUnverifiedException e) {
        log.error("Error while getting peer certificates", e);
        throw new CodedException(X_SSL_AUTH_FAILED,
                "Service provider " + "did not send correct authentication certificate");
    }
}

From source file:com.esri.geoevent.datastore.DataStoreProxyHostnameVerifier.java

@Override
public boolean verify(String hostname, SSLSession session) {
    try {/*w  w  w  .  j a v a  2 s . c  om*/
        final Certificate[] certs = session.getPeerCertificates();
        if (trustedCerts.contains(((X509Certificate) certs[0]))) {
            return true;
        }
        return verifier.verify(hostname, session);
    } catch (Exception e) {
        return false;
    }
}

From source file:ua.pp.msk.cliqr.CliQrHostnameVerifier.java

@Override
public boolean verify(String host, SSLSession sslSession) {
    try {//  w  w w.  ja  v a 2  s.c o  m
        Certificate[] peerCertificates = sslSession.getPeerCertificates();
        for (Certificate cert : peerCertificates) {
            verify(host, (X509Certificate) cert);
        }
    } catch (SSLException ex) {
        logger.warn("Cannot analize SSL certificates", ex);
    }
    return true;
}

From source file:org.jasig.portal.security.provider.saml.PublicKeyVerifyingSSLSocketFactory.java

/**
 * This method makes a connection to the server by utilizing the base class
 * method, but it adds a validation of the server's public key if one was
 * supplied previously.//www . j a  v a2  s  . co m
 * 
 * @see org.apache.http.conn.ssl.SSLSocketFactory#connectSocket(java.net.Socket, java.lang.String, int, java.net.InetAddress, int, org.apache.http.params.HttpParams)
 */
@Override
public Socket connectSocket(final Socket sock, final String host, final int port,
        final InetAddress localAddress, int localPort, final HttpParams params) throws IOException {
    SSLSocket newSocket = (SSLSocket) super.connectSocket(sock, host, port, localAddress, localPort, params);

    if (publicKey != null) {
        logger.debug("Verifying SSL Socket to {}:{} against configured public key {}",
                new Object[] { host, port, publicKey });

        SSLSession session = newSocket.getSession();
        Certificate[] certs = session.getPeerCertificates();
        boolean matchFound = false;

        for (int i = 0; i < certs.length; i++) {
            X509Certificate x509 = (X509Certificate) certs[i];
            PublicKey certKey = x509.getPublicKey();

            if (certKey.equals(publicKey)) {
                logger.debug("Validated public key against server key: {}", certKey);
                matchFound = true;
                break;
            }
            logger.debug("server key doesn't match public key: {} ", certKey);
        }
        if (!matchFound) {
            newSocket.close();
            throw new IOException("Unable to verify the server's public key");
        }
    }
    return newSocket;
}