Example usage for javax.net.ssl SSLSocket startHandshake

List of usage examples for javax.net.ssl SSLSocket startHandshake

Introduction

In this page you can find the example usage for javax.net.ssl SSLSocket startHandshake.

Prototype

public abstract void startHandshake() throws IOException;

Source Link

Document

Starts an SSL handshake on this connection.

Usage

From source file:eu.eubrazilcc.lvl.core.http.client.TrustedHttpsClient.java

private static final void importCertificate(final String url, final KeyStore trustStore) throws Exception {
    final URL url2 = new URL(url);
    final SSLContext sslContext = SSLContext.getInstance("TLS");
    final TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(trustStore);
    final X509TrustManager defaultTrustManager = (X509TrustManager) trustManagerFactory.getTrustManagers()[0];
    final SavingTrustManager trustManager = new SavingTrustManager(defaultTrustManager);
    sslContext.init(null, new TrustManager[] { trustManager }, null);
    final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
    final SSLSocket socket = (SSLSocket) sslSocketFactory.createSocket(url2.getHost(),
            url2.getPort() > 0 ? url2.getPort() : 443);
    socket.setSoTimeout(10000);//from  w ww.  j a  va  2 s .  c  o m
    try {
        socket.startHandshake();
        socket.close();
    } catch (SSLException e) {
    }

    final X509Certificate[] chain = trustManager.chain;
    if (chain == null) {
        LOGGER.error("Could not obtain server certificate chain from: " + url);
        return;
    }

    final MessageDigest sha1 = MessageDigest.getInstance("SHA1");
    final MessageDigest md5 = MessageDigest.getInstance("MD5");
    for (int i = 0; i < chain.length; i++) {
        final X509Certificate cert = chain[i];
        final String alias = url2.getHost() + "-" + (i + 1);
        if (!trustStore.containsAlias(alias)) {
            sha1.update(cert.getEncoded());
            md5.update(cert.getEncoded());
            LOGGER.trace("Importing certificate to trusted keystore >> " + "Subject: " + cert.getSubjectDN()
                    + ", Issuer: " + cert.getIssuerDN() + ", SHA1: " + printHexBinary(sha1.digest()) + ", MD5: "
                    + printHexBinary(md5.digest()) + ", Alias: " + alias);
            trustStore.setCertificateEntry(alias, cert);
        }
    }
}

From source file:Messenger.TorLib.java

public static void postToURL(String hostname, int port, String postKey, String data) throws IOException {
    Socket socket = TorSocket(hostname, port);
    SSLSocketFactory sslSf = (SSLSocketFactory) SSLSocketFactory.getDefault();
    SSLSocket sslSocket = (SSLSocket) sslSf.createSocket(socket, null, socket.getPort(), false);
    sslSocket.setUseClientMode(true);/*from w ww . ja  va  2s . com*/
    sslSocket.startHandshake();
    String path = "/" + postKey;
    BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(sslSocket.getOutputStream(), "UTF8"));
    wr.write("POST " + path + " HTTP/1.0\r\n");
    wr.write("Content-Length: " + data.length() + "\r\n");
    wr.write("Content-Type: application/x-www-form-urlencoded\r\n");
    wr.write("\r\n");

    wr.write(data);
    wr.flush();

    BufferedReader rd = new BufferedReader(new InputStreamReader(sslSocket.getInputStream()));
    String line;
    while ((line = rd.readLine()) != null) {
        System.out.println(line);
    }
    wr.close();
    rd.close();
    sslSocket.close();
}

From source file:Messenger.TorLib.java

/**
 * This method makes a http GET request for the specified resource to the specified hostname.
 * It uses the SOCKS proxy to a connection over Tor.
 * The DNS lookup is also done over Tor.
 * This method only uses port 443 for SSL.
 *
 * @param hostname hostname for target server.
 * @param port port to connect to./*from  w  ww.j a  v  a2 s .co  m*/
 * @param resource resource to lookup with GET request.
 * @return returns a JSON object.
 * @throws IOException
 * @throws JSONException
 */
public static JSONObject getJSON(String hostname, int port, String resource)
        throws IOException, JSONException, HttpException {
    //Create a SSL socket using Tor
    Socket socket = TorSocket(hostname, port);
    SSLSocketFactory sslSf = (SSLSocketFactory) SSLSocketFactory.getDefault();
    SSLSocket sslSocket = (SSLSocket) sslSf.createSocket(socket, null, socket.getPort(), false);
    sslSocket.setUseClientMode(true);
    sslSocket.startHandshake();
    openSockets.add(sslSocket);

    //Create the HTTP GET request and push it over the outputstream
    BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(sslSocket.getOutputStream(), "UTF8"));
    wr.write("GET /" + resource + " HTTP/1.0\r\n");
    wr.write("Host: " + hostname + "\r\n");
    wr.write("\r\n");
    wr.flush();

    //Listen for a response on the inputstream
    BufferedReader br = new BufferedReader(new InputStreamReader(sslSocket.getInputStream()));
    String t;
    boolean start = false;
    String output = "";
    while ((t = br.readLine()) != null) {
        if (t.equals("")) {
            start = true;
        }
        if (start) {
            output = output + t;
        }
    }
    br.close();
    wr.close();
    sslSocket.close();
    System.out.println(output);
    openSockets.remove(sslSocket);
    return new JSONObject(output);
}

From source file:android.net.SSLCertificateSocketFactory.java

/**
 * Verify the hostname of the certificate used by the other end of a
 * connected socket.  You MUST call this if you did not supply a hostname
 * to {@link #createSocket()}.  It is harmless to call this method
 * redundantly if the hostname has already been verified.
 *
 * <p>Wildcard certificates are allowed to verify any matching hostname,
 * so "foo.bar.example.com" is verified if the peer has a certificate
 * for "*.example.com".//from  ww w .ja va2  s .  c om
 *
 * @param socket An SSL socket which has been connected to a server
 * @param hostname The expected hostname of the remote server
 * @throws IOException if something goes wrong handshaking with the server
 * @throws SSLPeerUnverifiedException if the server cannot prove its identity
 *
 * @hide
 */
public static void verifyHostname(Socket socket, String hostname) throws IOException {
    if (!(socket instanceof SSLSocket)) {
        throw new IllegalArgumentException("Attempt to verify non-SSL socket");
    }

    if (!isSslCheckRelaxed()) {
        // The code at the start of OpenSSLSocketImpl.startHandshake()
        // ensures that the call is idempotent, so we can safely call it.
        SSLSocket ssl = (SSLSocket) socket;
        ssl.startHandshake();

        SSLSession session = ssl.getSession();
        if (session == null) {
            throw new SSLException("Cannot verify SSL socket without session");
        }
        if (!HttpsURLConnection.getDefaultHostnameVerifier().verify(hostname, session)) {
            throw new SSLPeerUnverifiedException("Cannot verify hostname: " + hostname);
        }
    }
}

From source file:org.wso2.carbon.identity.relyingparty.saml.IssuerCertificateUtil.java

public static Certificate readCertFromUrl(String url) throws Exception {

    URL hostURL = null;/*from  w  ww  . j av a 2  s.  c  o m*/
    String hostname = null;
    int port;
    SSLSocketFactory factory = null;
    SSLSocket socket = null;

    try {
        // Create the client socket
        hostURL = new URL(url);
        hostname = hostURL.getHost();

        // Check whether the url has a port stated explicitly. If its not present default to 443
        port = hostURL.getPort();
        if (port == -1) {
            port = 443;
        }
        factory = HttpsURLConnection.getDefaultSSLSocketFactory();
        socket = (SSLSocket) factory.createSocket(hostname, port);

        // Connect to the server
        socket.startHandshake();

        // Retrieve the server's certificate chain
        Certificate[] serverCerts = socket.getSession().getPeerCertificates();

        // The local certificate first followed by any certificate authorities.
        if (serverCerts != null && serverCerts.length > 0) {
            if (log.isDebugEnabled()) {
                log.debug("Return any associated certificates suceessfully" + url);
            }
            return serverCerts[0];
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Does not return any associated certificates" + url);
            }
            return null;
        }

    } finally {
        // Close the socket
        if (socket != null) {
            socket.close();
        }
    }
}

From source file:com.zacwolf.commons.crypto._CRYPTOfactory.java

public static KeyStore addSiteTrustChain(final String sitehostname, final int httpsport,
        final KeyStore keystore, final char[] passphrase) throws KeyStoreException, NoSuchAlgorithmException,
        CertificateException, IOException, KeyManagementException {
    final SSLContext context = SSLContext.getInstance("TLS");
    final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(keystore);//from w  w  w  .jav  a 2 s . c  o  m
    final X509TrustManager dtm = (X509TrustManager) tmf.getTrustManagers()[0];
    final MyTrustManager tm = new MyTrustManager(dtm);
    context.init(null, new TrustManager[] { tm }, null);
    final SSLSocketFactory factory = context.getSocketFactory();
    final SSLSocket socket = (SSLSocket) factory.createSocket(sitehostname, httpsport);
    socket.setSoTimeout(10000);
    try {
        System.out.println("Starting SSL handshake...");
        socket.startHandshake();
        socket.close();
        System.out.println("Certificate for server " + sitehostname + " is already trusted");
    } catch (SSLException e) {
        final X509Certificate[] chain = tm.chain;
        if (chain == null) {
            System.err.println("Could not obtain server certificate chain");
            return keystore;
        }
        System.out.println("Server sent " + chain.length + " certificate(s):");
        for (int i = 0; i < chain.length; i++) {
            final X509Certificate cert = chain[i];
            MessageDigest.getInstance("SHA1").update(cert.getEncoded());
            MessageDigest.getInstance("MD5").update(cert.getEncoded());
            final String alias = sitehostname + "-" + (i + 1);
            keystore.setCertificateEntry(alias, cert);
            System.out.println("Added certificate to keystore using alias '" + alias + "'");
        }
    }
    return keystore;
}

From source file:org.sonatype.nexus.apachehttpclient.NexusSSLConnectionSocketFactory.java

@Override
public Socket connectSocket(final int connectTimeout, final Socket socket, final HttpHost host,
        final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpContext context)
        throws IOException {
    checkNotNull(host);/* w w  w.  ja  v a 2  s.  c  o  m*/
    checkNotNull(remoteAddress);
    final Socket sock = socket != null ? socket : createSocket(context);
    if (localAddress != null) {
        sock.bind(localAddress);
    }
    try {
        sock.connect(remoteAddress, connectTimeout);
    } catch (final IOException e) {
        Closeables.close(sock, true);
        throw e;
    }
    // Setup SSL layering if necessary
    if (sock instanceof SSLSocket) {
        final SSLSocket sslsock = (SSLSocket) sock;
        sslsock.startHandshake();
        verifyHostname(sslsock, host.getHostName());
        return sock;
    } else {
        return createLayeredSocket(sock, host.getHostName(), remoteAddress.getPort(), context);
    }
}

From source file:org.sonatype.nexus.apachehttpclient.NexusSSLConnectionSocketFactory.java

@Override
public Socket createLayeredSocket(final Socket socket, final String target, final int port,
        final HttpContext context) throws IOException {
    checkNotNull(socket);/*from  ww w  .  j  av  a2s  . c  o m*/
    checkNotNull(target);
    final SSLSocket sslsock = (SSLSocket) select(context).createSocket(socket, target, port, true);
    sslsock.startHandshake();
    verifyHostname(sslsock, target);
    return sslsock;
}

From source file:org.kuali.mobility.push.factory.iOSFeedbackConnectionFactory.java

@Override
public SSLSocket makeObject() throws Exception {
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    keyStore.load(certPath.getInputStream(), certPassword.toCharArray());
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("sunx509");
    keyManagerFactory.init(keyStore, certPassword.toCharArray());
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("sunx509");
    trustManagerFactory.init(keyStore);/* w w  w  .  j  av  a2 s  .co  m*/
    SSLContext sslCtx = SSLContext.getInstance("TLS");
    sslCtx.init(keyManagerFactory.getKeyManagers(), null, null);
    SSLSocketFactory sslSocketFactory = sslCtx.getSocketFactory();
    SSLSocket socket = (SSLSocket) sslSocketFactory.createSocket(host, port);
    socket.startHandshake();
    return socket;
}

From source file:org.sonatype.nexus.internal.httpclient.NexusSSLConnectionSocketFactory.java

@Override
@IgnoreJRERequirement//  w ww. jav a 2s .c  o m
public Socket connectSocket(final int connectTimeout, final Socket socket, final HttpHost host,
        final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpContext context)
        throws IOException {
    checkNotNull(host);
    checkNotNull(remoteAddress);
    final Socket sock = socket != null ? socket : createSocket(context);
    if (localAddress != null) {
        sock.bind(localAddress);
    }
    // NEXUS-6838: Server Name Indication support, a TLS feature that allows SSL
    // "virtual hosting" (multiple certificates) over single IP address + port.
    // Some CDN solutions requires this for HTTPS, as they choose certificate
    // to use based on "expected" hostname that is being passed here below
    // and is used during SSL handshake. Requires Java7+
    if (sock instanceof SSLSocketImpl) {
        ((SSLSocketImpl) sock).setHost(host.getHostName());
    }
    try {
        sock.connect(remoteAddress, connectTimeout);
    } catch (final IOException e) {
        Closeables.close(sock, true);
        throw e;
    }
    // Setup SSL layering if necessary
    if (sock instanceof SSLSocket) {
        final SSLSocket sslsock = (SSLSocket) sock;
        sslsock.startHandshake();
        verifyHostname(sslsock, host.getHostName());
        return sock;
    } else {
        return createLayeredSocket(sock, host.getHostName(), remoteAddress.getPort(), context);
    }
}