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:de.vanita5.twittnuker.util.net.ssl.HostResolvedSSLConnectionSocketFactory.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 {
    Args.notNull(host, "HTTP host");
    Args.notNull(remoteAddress, "Remote address");
    final Socket sock = socket != null ? socket : createSocket(context);
    if (localAddress != null) {
        sock.bind(localAddress);/*from  www  . j  av  a2  s.c o  m*/
    }
    try {
        sock.connect(remoteAddress, connectTimeout);
    } catch (final IOException ex) {
        try {
            sock.close();
        } catch (final IOException ignore) {
        }
        throw ex;
    }
    // Setup SSL layering if necessary
    if (sock instanceof SSLSocket) {
        final SSLSocket sslsock = (SSLSocket) sock;
        sslsock.startHandshake();
        verifyHostname(sslsock, host.getHostName(), context);
        return sock;
    } else
        return createLayeredSocket(sock, host.getHostName(), remoteAddress.getPort(), context);
}

From source file:com.leetchi.api.client.ssl.SSLConnectionSocketFactory.java

public Socket connectSocket(final int connectTimeout, final Socket socket, final HttpHost host,
        final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpContext context)
        throws IOException {
    Args.notNull(host, "HTTP host");
    Args.notNull(remoteAddress, "Remote address");
    final Socket sock = socket != null ? socket : createSocket(context);
    if (localAddress != null) {
        sock.bind(localAddress);/*from  w ww .j a va2 s  . c  om*/
    }
    try {
        sock.connect(remoteAddress, connectTimeout);
    } catch (final IOException ex) {
        try {
            sock.close();
        } catch (final IOException ignore) {
        }
        throw ex;
    }
    // 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:com.myJava.file.driver.remote.ftp.FTPSClient.java

protected Socket _openDataConnection_(int command, String arg) throws IOException {
    SSLSocket socket = (SSLSocket) super._openDataConnection_(command, arg);
    if (socket != null) {
        socket.setEnableSessionCreation(true);
        socket.setUseClientMode(true);/*from  ww w . j  a  v  a 2 s  .c o  m*/
        socket.startHandshake();
    }
    return socket;
}

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

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

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

@Test
public void testValidateUnilateralTLSTrust() throws Exception {
    LOG.debug("validate using unilateral TLS Trust.");

    // Retrieve server public key
    SSLTrustManager.initialize();/*from   w  w  w  . jav a 2  s . co  m*/
    SSLSocketFactory factory = HttpsURLConnection.getDefaultSSLSocketFactory();
    SSLSocket socket = (SSLSocket) factory.createSocket(TestUtils.XKMS_WS_HOST, port);
    socket.startHandshake();
    Certificate[] serverCerts = socket.getSession().getPeerCertificates();
    PublicKey publicKey = serverCerts[0].getPublicKey();
    LOG.debug("server public key: " + publicKey);
    socket.close();

    /*
     * Override default verification that CN of server SSL certificate has
     * to be equal to the hostname.
     */
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return hostname.equals(TestUtils.XKMS_WS_HOST);
        }
    });

    // setup
    List<X509Certificate> signCertificateChain = TestUtils.getSignCertificateChain();
    XKMS2Client client = new XKMS2Client(
            "https://" + TestUtils.XKMS_WS_HOST + ":" + port + TestUtils.XKMS_WS_CONTEXT_PATH);
    client.setServicePublicKey(publicKey);

    /*
     * Operate: validate non repudiation
     */
    client.validate(TrustServiceDomains.BELGIAN_EID_NON_REPUDIATION_TRUST_DOMAIN, signCertificateChain);
}

From source file:eu.eidas.auth.engine.metadata.impl.BaseMetadataFetcher.java

/**
 * Override this method to plug your own SSLSocketFactory.
 * <p>/*from w  ww. j  a  v a2  s .  c  o  m*/
 * This default implementation relies on the default one from the JVM, i.e. using the default trustStore
 * ($JRE/lib/security/cacerts).
 *
 * @return the SecureProtocolSocketFactory instance to be used to connect to https metadata URLs.
 */
@Nonnull
protected SecureProtocolSocketFactory newSslSocketFactory() {

    HostnameVerifier hostnameVerifier;

    if (!Boolean.getBoolean(DefaultBootstrap.SYSPROP_HTTPCLIENT_HTTPS_DISABLE_HOSTNAME_VERIFICATION)) {
        hostnameVerifier = new StrictHostnameVerifier();
    } else {
        hostnameVerifier = org.apache.commons.ssl.HostnameVerifier.ALLOW_ALL;
    }

    TLSProtocolSocketFactory tlsProtocolSocketFactory = new TLSProtocolSocketFactory(null, null,
            hostnameVerifier) {
        @Override
        protected void verifyHostname(Socket socket) throws SSLException {
            if (socket instanceof SSLSocket) {
                SSLSocket sslSocket = (SSLSocket) socket;
                try {
                    sslSocket.startHandshake();
                } catch (IOException e) {
                    throw new SSLException(e);
                }
                SSLSession sslSession = sslSocket.getSession();
                if (!sslSession.isValid()) {
                    throw new SSLException("SSLSession was invalid: Likely implicit handshake failure: "
                            + "Set system property javax.net.debug=all for details");
                }
                super.verifyHostname(sslSocket);
            }
        }
    };

    Protocol.registerProtocol("https", new Protocol("https", tlsProtocolSocketFactory, 443));

    return tlsProtocolSocketFactory;
}

From source file:net.lightbody.bmp.proxy.jetty.http.ClientCertAuthenticator.java

/** 
 * @return UserPrinciple if authenticated or null if not. If
 * Authentication fails, then the authenticator may have committed
 * the response as an auth challenge or redirect.
 * @exception IOException /*w  w w .  j a v a  2 s .  com*/
 */
public Principal authenticate(UserRealm realm, String pathInContext, HttpRequest request, HttpResponse response)
        throws IOException {
    java.security.cert.X509Certificate[] certs = (java.security.cert.X509Certificate[]) request
            .getAttribute("javax.servlet.request.X509Certificate");

    if (response != null && (certs == null || certs.length == 0 || certs[0] == null)) {
        // No certs available so lets try and force the issue

        // Get the SSLSocket
        Object s = HttpConnection.getHttpConnection().getConnection();
        if (!(s instanceof SSLSocket))
            return null;
        SSLSocket socket = (SSLSocket) s;

        if (!socket.getNeedClientAuth()) {
            // Need to re-handshake
            socket.setNeedClientAuth(true);
            socket.startHandshake();

            // Need to wait here - but not forever. The Handshake
            // Listener API does not look like a good option to
            // avoid waiting forever.  So we will take a slightly
            // busy timelimited approach. For now:
            for (int i = (_maxHandShakeSeconds * 4); i-- > 0;) {
                certs = (java.security.cert.X509Certificate[]) request
                        .getAttribute("javax.servlet.request.X509Certificate");
                if (certs != null && certs.length > 0 && certs[0] != null)
                    break;
                try {
                    Thread.sleep(250);
                } catch (Exception e) {
                    break;
                }
            }
        }
    }

    if (certs == null || certs.length == 0 || certs[0] == null)
        return null;

    Principal principal = certs[0].getSubjectDN();
    if (principal == null)
        principal = certs[0].getIssuerDN();
    String username = principal == null ? "clientcert" : principal.getName();

    Principal user = realm.authenticate(username, certs, request);

    request.setAuthType(SecurityConstraint.__CERT_AUTH);
    if (user != null)
        request.setAuthUser(user.getName());
    request.setUserPrincipal(user);
    return user;
}

From source file:com.subgraph.vega.internal.http.proxy.VegaHttpService.java

private void handleConnect(VegaHttpServerConnection conn, HttpRequest request, HttpContext context)
        throws IOException, HttpException {
    final HttpHost host = createHostForConnectUri(request.getRequestLine().getUri());
    final SSLSocket sslSocket = createSSLSocketForHost(host, conn.getSocket());

    sendResponseOk(conn, context);//from w w  w .j av a  2s  .  c o  m
    conn.rebindWithSSL(sslSocket, host);

    try {
        sslSocket.startHandshake();
    } catch (SSLHandshakeException e) {
        conn.close();
        return;
    }
    delegatedHttpService.handleRequest(conn, context);
}

From source file:com.myJava.file.driver.remote.ftp.SecuredSocketFactory.java

private void init(SSLSocket socket) throws IOException {
    socket.setEnableSessionCreation(true);
    socket.setUseClientMode(true);//from ww w  .j  a  v a 2 s  . c om
    socket.startHandshake();
    client.setNegociated();
}

From source file:davmail.util.ClientCertificateTest.java

public void testClientSocketFactory()
        throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException,
        KeyManagementException, UnrecoverableKeyException, InvalidAlgorithmParameterException {

    //System.setProperty("javax.net.ssl.trustStoreProvider", "SunMSCAPI");
    //System.setProperty("javax.net.ssl.trustStoreType", "Windows-ROOT");
    System.setProperty("javax.net.ssl.trustStore", "cacerts");
    System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
    System.setProperty("javax.net.ssl.trustStoreType", "JKS");

    //SSLSocket sslSock = (SSLSocket)new DavGatewaySSLProtocolSocketFactory().createSocket("localhost", 443);
    SSLSocket sslSock = (SSLSocket) createSSLContext().getSocketFactory().createSocket("localhost", 443);
    sslSock.startHandshake();

}