Example usage for javax.net.ssl SSLSession getPeerHost

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

Introduction

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

Prototype

public String getPeerHost();

Source Link

Document

Returns the host name of the peer in this session.

Usage

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

public static void main(String args[]) throws Exception {
    System.setProperty("javax.net.ssl.keyStore", "lfkeystore2");
    System.setProperty("javax.net.ssl.keyStorePassword", "wshr.ut");

    SSLServerSocketFactory ssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
    ServerSocket ss = ssf.createServerSocket(5432);
    while (true) {
        Socket s = ss.accept();/*from ww  w  .  j ava  2  s  .c om*/
        SSLSession session = ((SSLSocket) s).getSession();
        Certificate[] cchain2 = session.getLocalCertificates();
        for (int i = 0; i < cchain2.length; i++) {
            System.out.println(((X509Certificate) cchain2[i]).getSubjectDN());
        }
        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());

        PrintStream out = new PrintStream(s.getOutputStream());
        out.println("Hi");
        out.close();
        s.close();
    }

}

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());
    }//from w  ww . j av a2 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:com.sun.socialsite.pojos.App.java

public static App readFromURL(URL url) throws Exception {
    HttpURLConnection con = (HttpURLConnection) (url.openConnection());
    con.setDoOutput(false);/*from   ww w  . j av a2 s .c  o m*/
    // TODO: figure out why this is necessary for HTTPS URLs
    if (con instanceof HttpsURLConnection) {
        HostnameVerifier hv = new HostnameVerifier() {
            public boolean verify(String urlHostName, SSLSession session) {
                if ("localhost".equals(urlHostName) && "127.0.0.1".equals(session.getPeerHost())) {
                    return true;
                } else {
                    log.warn("URL Host: " + urlHostName + " vs. " + session.getPeerHost());
                    return false;
                }
            }
        };
        ((HttpsURLConnection) con).setDefaultHostnameVerifier(hv);
    }
    con.connect();
    if (con.getResponseCode() != HttpURLConnection.HTTP_OK) {
        throw new RuntimeException(con.getResponseMessage());
    }
    InputStream in = con.getInputStream();
    return readFromStream(in, url);
}

From source file:ie.aib.nbp.aibssl.AibHostVerifier.java

@Override
public boolean verify(String host, SSLSession session) {
    String sslHost = session.getPeerHost();
    System.out.println("Host=" + host);
    System.out.println("SSL Host=" + sslHost);
    if (host.equals(sslHost)) {
        return true;
    } else {//from  w  ww.  j  a va  2  s . co m
        return false;
    }
}

From source file:org.orcid.examples.jopmts.impl.SSLConfig.java

@Override
public void afterPropertiesSet() throws Exception {
    trustSelfSignedSSL();/*from  w  w  w. ja v  a2  s  .c o m*/

    HostnameVerifier hv = new HostnameVerifier() {
        public boolean verify(String urlHostName, SSLSession session) {
            System.out.println("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost());
            return true;
        }

    };
    HttpsURLConnection.setDefaultHostnameVerifier(hv);
}

From source file:com.ntsync.android.sync.client.MySSLSocketFactory.java

private void verifyHostname(SSLSocket socket) throws SSLPeerUnverifiedException {
    SSLSession session = socket.getSession();
    String hostname = session.getPeerHost();

    X509Certificate[] certs = session.getPeerCertificateChain();
    if (certs == null || certs.length == 0) {
        throw new SSLPeerUnverifiedException("No server certificates found!");
    }/*from w  ww  . j a v  a 2 s  . c  o  m*/

    // 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.isLoggable(TAG, Log.DEBUG)) {
        Log.d(TAG, "Server certificate chain:");
        for (int i = 0; i < certs.length; i++) {
            Log.d(TAG, "X509Certificate[" + i + "]=" + certs[i]);
        }
    }
    // get the common name from the first cert
    String cn = getCN(dn);
    if (hostname != null && hostname.equalsIgnoreCase(cn)) {
        if (Log.isLoggable(TAG, Log.DEBUG)) {
            Log.d(TAG, "Target hostname valid: " + cn);
        }
    } else {
        if (BuildConfig.DEBUG) {
            Log.w(TAG, "HTTPS hostname invalid: expected '" + hostname + "', received '" + cn + "'");
            return;
        }
        throw new SSLPeerUnverifiedException(
                "HTTPS hostname invalid: expected '" + hostname + "', received '" + cn + "'");
    }
}

From source file:com.ksc.http.conn.ssl.SdkTLSSocketFactory.java

/**
 * Invalidates all SSL/TLS sessions in {@code sessionContext} associated with {@code remoteAddress}.
 *
 * @param sessionContext collection of SSL/TLS sessions to be (potentially) invalidated
 * @param remoteAddress  associated with sessions to invalidate
 *//*  w w  w  .j av a 2s . c o m*/
private void clearSessionCache(final SSLSessionContext sessionContext, final InetSocketAddress remoteAddress) {
    final String hostName = remoteAddress.getHostName();
    final int port = remoteAddress.getPort();
    final Enumeration<byte[]> ids = sessionContext.getIds();

    if (ids == null) {
        return;
    }

    while (ids.hasMoreElements()) {
        final byte[] id = ids.nextElement();
        final SSLSession session = sessionContext.getSession(id);
        if (session != null && session.getPeerHost() != null && session.getPeerHost().equalsIgnoreCase(hostName)
                && session.getPeerPort() == port) {
            session.invalidate();
            if (LOG.isDebugEnabled()) {
                LOG.debug("Invalidated session " + session);
            }
        }
    }
}

From source file:com.amazonaws.http.conn.ssl.SdkTLSSocketFactory.java

/**
 * Invalidates all SSL/TLS sessions in {@code sessionContext} associated with {@code remoteAddress}.
 * @param sessionContext collection of SSL/TLS sessions to be (potentially) invalidated
 * @param remoteAddress associated with sessions to invalidate
 *//*from w  w  w  .  j ava  2 s .c  om*/
private void clearSessionCache(final SSLSessionContext sessionContext, final InetSocketAddress remoteAddress) {
    final String hostName = remoteAddress.getHostName();
    final int port = remoteAddress.getPort();
    final Enumeration<byte[]> ids = sessionContext.getIds();

    if (ids == null) {
        return;
    }

    while (ids.hasMoreElements()) {
        final byte[] id = ids.nextElement();
        final SSLSession session = sessionContext.getSession(id);
        if (session != null && session.getPeerHost() != null && session.getPeerHost().equalsIgnoreCase(hostName)
                && session.getPeerPort() == port) {
            session.invalidate();
            if (log.isDebugEnabled()) {
                log.debug("Invalidated session " + session);
            }
        }
    }
}

From source file:com.sun.socialsite.web.rest.servlets.ProxyServlet.java

/**
 * Handles the HTTP <code>GET</code> method.
 * @param req servlet request//w  w w.  j a  v a2s .  c  o  m
 * @param resp servlet response
 */
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {

        URL url = getURL(req, req.getParameter("uri"));
        HttpURLConnection con = (HttpURLConnection) (url.openConnection());
        con.setAllowUserInteraction(false);
        con.setUseCaches(false);

        // TODO: figure out why this is necessary for HTTPS URLs
        if (con instanceof HttpsURLConnection) {
            HostnameVerifier hv = new HostnameVerifier() {
                public boolean verify(String urlHostName, SSLSession session) {
                    if ("localhost".equals(urlHostName) && "127.0.0.1".equals(session.getPeerHost())) {
                        return true;
                    } else {
                        log.error("URL Host: " + urlHostName + " vs. " + session.getPeerHost());
                        return false;
                    }
                }
            };
            ((HttpsURLConnection) con).setDefaultHostnameVerifier(hv);
        }
        // pass along all appropriate HTTP headers
        Enumeration headerNames = req.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String hname = (String) headerNames.nextElement();
            if (!unproxiedHeaders.contains(hname.toLowerCase())) {
                con.addRequestProperty(hname, req.getHeader(hname));
            }
        }
        con.connect();

        // read result headers of GET, write to response
        Map<String, List<String>> headers = con.getHeaderFields();
        for (String key : headers.keySet()) {
            if (key != null) { // TODO: why is this check necessary!
                List<String> header = headers.get(key);
                if (header.size() > 0)
                    resp.setHeader(key, header.get(0));
            }
        }

        InputStream in = con.getInputStream();
        OutputStream out = resp.getOutputStream();
        final byte[] buf = new byte[8192];
        int len;
        while ((len = in.read(buf)) != -1) {
            out.write(buf, 0, len);
        }
        out.flush();

    } catch (Exception e) {
        throw new ServletException(e);
    }
}