当前位置: 首页>>代码示例>>Java>>正文


Java SSLSocket.startHandshake方法代码示例

本文整理汇总了Java中javax.net.ssl.SSLSocket.startHandshake方法的典型用法代码示例。如果您正苦于以下问题:Java SSLSocket.startHandshake方法的具体用法?Java SSLSocket.startHandshake怎么用?Java SSLSocket.startHandshake使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在javax.net.ssl.SSLSocket的用法示例。


在下文中一共展示了SSLSocket.startHandshake方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: upgradeToTls

import javax.net.ssl.SSLSocket; //导入方法依赖的package包/类
private void upgradeToTls(Socket socket) throws KeyStoreException, IOException, NoSuchAlgorithmException,
        CertificateException, UnrecoverableKeyException, KeyManagementException {

    KeyStore keyStore = keyStoreProvider.getKeyStore();

    String defaultAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(defaultAlgorithm);
    keyManagerFactory.init(keyStore, keyStoreProvider.getPassword());

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(keyManagerFactory.getKeyManagers(), null, null);
    SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

    SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(
            socket, socket.getInetAddress().getHostAddress(), socket.getPort(), true);
    sslSocket.setUseClientMode(false);
    sslSocket.startHandshake();

    input = Okio.buffer(Okio.source(sslSocket.getInputStream()));
    output = Okio.buffer(Okio.sink(sslSocket.getOutputStream()));
}
 
开发者ID:philipwhiuk,项目名称:q-mail,代码行数:22,代码来源:MockSmtpServer.java

示例2: initSocket

import javax.net.ssl.SSLSocket; //导入方法依赖的package包/类
@Override
protected void initSocket() throws IOException {
    SSLSocket sslSocket = (SSLSocket) socketFactory.createSocket(destination.getAddress(), destination.getPort());

    sslSocket.addHandshakeCompletedListener(handshakeCompletedEvent -> {
                try {
                    LOGGER.debug("Connected [" + handshakeCompletedEvent.getSource() + ", " + sslSocket.getSession().getPeerCertificateChain()[0].getSubjectDN() + "]");
                } catch (SSLPeerUnverifiedException e) {
                    LOGGER.warn(e.getMessage(), e);
                }
            }
    );
    sslSocket.startHandshake();

    this.socket = sslSocket;
}
 
开发者ID:ARMmbed,项目名称:java-coap,代码行数:17,代码来源:SSLSocketClientTransport.java

示例3: verifyHostname

import javax.net.ssl.SSLSocket; //导入方法依赖的package包/类
/**
 * Verify hostname against certificate
 * @param sslSocket Socket
 * @param host Host name
 * @throws IOException Exception if host name is not verified
 */
private void verifyHostname(SSLSocket sslSocket, String host) throws IOException {
    // Make sure we started handshake before verifying
    sslSocket.startHandshake();

    SSLSession session = sslSocket.getSession();
    if (session == null) {
        throw new SSLException("Hostname '" + host + "' was not verified (no session)");
    }
    if (!hostnameVerifier.verify(host, session)) {
        throw new SSLPeerUnverifiedException("Hostname '" + host + "' was not verified (" + session.getPeerPrincipal() + ")");
    }
    if (Logger.DEBUG) { Log.d(TAG, "Connected to " + session.getPeerHost() + " using " + session.getProtocol() + " (" + session.getCipherSuite() + ")"); }
}
 
开发者ID:bfabiszewski,项目名称:ulogger-android,代码行数:20,代码来源:TlsSocketFactory.java

示例4: testSSLSocket

import javax.net.ssl.SSLSocket; //导入方法依赖的package包/类
private boolean testSSLSocket(SSLSocket sslSocket) {
       try {
        if(DEBUG_ALL) System.out.println("Starting SSL handshake");
     sslSocket.setSoTimeout(0);
           sslSocket.startHandshake();
           return true;
       } catch (Exception e) {
        if(DEBUG_ALL) e.printStackTrace();
           return false;
       }
}
 
开发者ID:jeffreyshen19,项目名称:Virtual-IoT-Server,代码行数:12,代码来源:SSLClientSocket.java

示例5: processHandshakeFailure

import javax.net.ssl.SSLSocket; //导入方法依赖的package包/类
private void processHandshakeFailure(Socket raw) throws Exception {
  SSLContext context = SSLContext.getInstance("TLS");
  context.init(null, new TrustManager[] {UNTRUSTED_TRUST_MANAGER}, new SecureRandom());
  SSLSocketFactory sslSocketFactory = context.getSocketFactory();
  SSLSocket socket = (SSLSocket) sslSocketFactory.createSocket(
      raw, raw.getInetAddress().getHostAddress(), raw.getPort(), true);
  try {
    socket.startHandshake(); // we're testing a handshake failure
    throw new AssertionError();
  } catch (IOException expected) {
  }
  socket.close();
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:14,代码来源:MockWebServer.java

示例6: get

import javax.net.ssl.SSLSocket; //导入方法依赖的package包/类
public static void get(String host, int port, KeyStore keyStore) throws Exception {
  TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
  tmf.init(keyStore);
  
  X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
  SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
  
  SSLContext sslContext = SSLContext.getInstance("TLS");
  sslContext.init(null, new TrustManager[] {tm}, null);
  
  LOGGER.info("Iniciando conexão com: " + host + ":" + port + "...");
  SSLSocket socket = (SSLSocket) sslContext.getSocketFactory().createSocket(host, port);
  
  try {
    socket.setSoTimeout(30 * 1000);
    socket.startHandshake();
    socket.close();
  } catch (Exception e) {
    LOGGER.info(e.toString());
  } 

  X509Certificate[] chain = tm.chain;
  if (chain == null) {
    LOGGER.info("Não foi possivel obter a cadeia de certificados");
  }

  LOGGER.info("O servidor enviou " + chain.length + " certificado(s):");
  MessageDigest sha1 = MessageDigest.getInstance("SHA1");
  MessageDigest md5 = MessageDigest.getInstance("MD5");
  for (int i = 0; i < chain.length; i++) {
    X509Certificate cert = chain[i];
    sha1.update(cert.getEncoded());
    md5.update(cert.getEncoded());

    String alias = host + "-" + (i);
    keyStore.setCertificateEntry(alias, cert);
    LOGGER.info("Certificado adicionado usando alias: '" + alias + "'");
  }
}
 
开发者ID:pablopdomingos,项目名称:nfse,代码行数:40,代码来源:NFSeGeraCadeiaCertificados.java

示例7: sslNegotiation

import javax.net.ssl.SSLSocket; //导入方法依赖的package包/类
/**
 * SSL/TLS negotiation. Acquires an SSL socket of a control
 * connection and carries out handshake processing.
 * @throws java.io.IOException If server negotiation fails
 */
protected void sslNegotiation() throws IOException {
    plainSocket = _socket_;
    initSslContext();

    SSLSocketFactory ssf = context.getSocketFactory();
    String ip = _socket_.getInetAddress().getHostAddress();
    int port = _socket_.getPort();
    SSLSocket socket =
        (SSLSocket) ssf.createSocket(_socket_, ip, port, false);
    socket.setEnableSessionCreation(isCreation);
    socket.setUseClientMode(isClientMode);
    // server mode
    if (!isClientMode) {
        socket.setNeedClientAuth(isNeedClientAuth);
        socket.setWantClientAuth(isWantClientAuth);
    }

    if (protocols != null) {
        socket.setEnabledProtocols(protocols);
    }
    if (suites != null) {
        socket.setEnabledCipherSuites(suites);
    }
    socket.startHandshake();

    _socket_ = socket;
    _controlInput_ = new BufferedReader(new InputStreamReader(
            socket .getInputStream(), getControlEncoding()));
    _controlOutput_ = new BufferedWriter(new OutputStreamWriter(
            socket.getOutputStream(), getControlEncoding()));
}
 
开发者ID:archos-sa,项目名称:aos-FileCoreLibrary,代码行数:37,代码来源:FTPSClient.java

示例8: connectSocket

import javax.net.ssl.SSLSocket; //导入方法依赖的package包/类
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);
    }
    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);
    }
}
 
开发者ID:mozilla-mobile,项目名称:FirefoxData-android,代码行数:33,代码来源:SSLSocketFactory.java

示例9: createLayeredSocket

import javax.net.ssl.SSLSocket; //导入方法依赖的package包/类
public Socket createLayeredSocket(
        final Socket socket,
        final String target,
        final int port,
        final HttpContext context) throws IOException {
    final SSLSocket sslsock = (SSLSocket) this.socketfactory.createSocket(
            socket,
            target,
            port,
            true);
    internalPrepareSocket(sslsock);
    sslsock.startHandshake();
    verifyHostname(sslsock, target);
    return sslsock;
}
 
开发者ID:mozilla-mobile,项目名称:FirefoxData-android,代码行数:16,代码来源:SSLSocketFactory.java

示例10: verifyHostName

import javax.net.ssl.SSLSocket; //导入方法依赖的package包/类
/**
    * Verifies that the given hostname in certicifate is the hostname we are trying to connect to
    * http://www.cvedetails.com/cve/CVE-2012-5783/
    * @param host
    * @param ssl
    * @throws IOException
    */
   
private static void verifyHostName(String host, SSLSocket ssl)
		throws IOException {
	if (host == null) {
		throw new IllegalArgumentException("host to verify was null");
	}

	SSLSession session = ssl.getSession();
	if (session == null) {
           // In our experience this only happens under IBM 1.4.x when
           // spurious (unrelated) certificates show up in the server's chain.
           // Hopefully this will unearth the real problem:
		InputStream in = ssl.getInputStream();
		in.available();
           /*
                If you're looking at the 2 lines of code above because you're
                running into a problem, you probably have two options:

                   #1.  Clean up the certificate chain that your server
                        is presenting (e.g. edit "/etc/apache2/server.crt" or
                        wherever it is your server's certificate chain is
                        defined).

                                            OR

                   #2.   Upgrade to an IBM 1.5.x or greater JVM, or switch to a
                         non-IBM JVM.
             */

           // If ssl.getInputStream().available() didn't cause an exception,
           // maybe at least now the session is available?
		session = ssl.getSession();
		if (session == null) {
               // If it's still null, probably a startHandshake() will
               // unearth the real problem.
			ssl.startHandshake();

               // Okay, if we still haven't managed to cause an exception,
               // might as well go for the NPE.  Or maybe we're okay now?
			session = ssl.getSession();
		}
	}

	Certificate[] certs = session.getPeerCertificates();
	verifyHostName(host.trim().toLowerCase(Locale.US),  (X509Certificate) certs[0]);
}
 
开发者ID:jenkinsci,项目名称:lib-commons-httpclient,代码行数:54,代码来源:SSLProtocolSocketFactory.java

示例11: upgradeToTls

import javax.net.ssl.SSLSocket; //导入方法依赖的package包/类
/**
 * Create an {@code SSLSocket} and perform the TLS handshake and certificate
 * validation.
 */
private void upgradeToTls(TunnelRequest tunnelRequest) throws IOException {
  Platform platform = Platform.get();

  // Make an SSL Tunnel on the first message pair of each SSL + proxy connection.
  if (requiresTunnel()) {
    makeTunnel(tunnelRequest);
  }

  // Create the wrapper over connected socket.
  socket = route.address.sslSocketFactory
      .createSocket(socket, route.address.uriHost, route.address.uriPort, true /* autoClose */);
  SSLSocket sslSocket = (SSLSocket) socket;
  if (route.modernTls) {
    platform.enableTlsExtensions(sslSocket, route.address.uriHost);
  } else {
    platform.supportTlsIntolerantServer(sslSocket);
  }

  boolean useNpn = route.modernTls && route.address.transports.contains("spdy/3");
  if (useNpn) {
    platform.setNpnProtocols(sslSocket, NPN_PROTOCOLS);
  }

  // Force handshake. This can throw!
  sslSocket.startHandshake();

  // Verify that the socket's certificates are acceptable for the target host.
  if (!route.address.hostnameVerifier.verify(route.address.uriHost, sslSocket.getSession())) {
    throw new IOException("Hostname '" + route.address.uriHost + "' was not verified");
  }

  out = sslSocket.getOutputStream();
  in = sslSocket.getInputStream();
  streamWrapper();

  byte[] selectedProtocol;
  if (useNpn && (selectedProtocol = platform.getNpnSelectedProtocol(sslSocket)) != null) {
    if (Arrays.equals(selectedProtocol, SPDY3)) {
      sslSocket.setSoTimeout(0); // SPDY timeouts are set per-stream.
      spdyConnection = new SpdyConnection.Builder(route.address.getUriHost(), true, in, out)
          .build();
      spdyConnection.sendConnectionHeader();
    } else if (!Arrays.equals(selectedProtocol, HTTP_11)) {
      throw new IOException(
          "Unexpected NPN transport " + new String(selectedProtocol, "ISO-8859-1"));
    }
  }
}
 
开发者ID:aabognah,项目名称:LoRaWAN-Smart-Parking,代码行数:53,代码来源:Connection.java

示例12: startHandshake

import javax.net.ssl.SSLSocket; //导入方法依赖的package包/类
private SSLSocket startHandshake(SSLSocketFactory factory)
    throws IOException {

    if (ldapConnection == null) {
        throw new IllegalStateException("LDAP connection has not been set."
            + " TLS requires an existing LDAP connection.");
    }

    if (factory != currentFactory) {
        // Create SSL socket layered over the existing connection
        sslSocket = (SSLSocket) factory.createSocket(ldapConnection.sock,
            ldapConnection.host, ldapConnection.port, false);
        currentFactory = factory;

        if (debug) {
            System.out.println("StartTLS: Created socket : " + sslSocket);
        }
    }

    if (suites != null) {
        sslSocket.setEnabledCipherSuites(suites);
        if (debug) {
            System.out.println("StartTLS: Enabled cipher suites");
        }
    }

    // Connection must be quite for handshake to proceed

    try {
        if (debug) {
            System.out.println(
                    "StartTLS: Calling sslSocket.startHandshake");
        }
        sslSocket.startHandshake();
        if (debug) {
            System.out.println(
                    "StartTLS: + Finished sslSocket.startHandshake");
        }

        // Replace original streams with the new SSL streams
        ldapConnection.replaceStreams(sslSocket.getInputStream(),
            sslSocket.getOutputStream());
        if (debug) {
            System.out.println("StartTLS: Replaced IO Streams");
        }

    } catch (IOException e) {
        if (debug) {
            System.out.println("StartTLS: Got IO error during handshake");
            e.printStackTrace();
        }

        sslSocket.close();
        isClosed = true;
        throw e;   // pass up exception
    }

    return sslSocket;
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:60,代码来源:StartTlsResponseImpl.java

示例13: testRenegotiateWorks

import javax.net.ssl.SSLSocket; //导入方法依赖的package包/类
@Test
public void testRenegotiateWorks() throws Exception {
    Tomcat tomcat = getTomcatInstance();

    Assume.assumeTrue("SSL renegotiation has to be supported for this test",
            TesterSupport.isRenegotiationSupported(getTomcatInstance()));

    File appDir = new File(getBuildDirectory(), "webapps/examples");
    // app dir is relative to server home
    tomcat.addWebapp(null, "/examples", appDir.getAbsolutePath());

    TesterSupport.initSsl(tomcat);

    tomcat.start();

    SSLContext sslCtx = SSLContext.getInstance("TLS");
    sslCtx.init(null, TesterSupport.getTrustManagers(), null);
    SSLSocketFactory socketFactory = 
            new TesterSupport.NoSSLv2SocketFactory(sslCtx.getSocketFactory());
    SSLSocket socket = (SSLSocket) socketFactory.createSocket("localhost",
            getPort());

    OutputStream os = socket.getOutputStream();

    os.write("GET /examples/servlets/servlet/HelloWorldExample HTTP/1.1\n".getBytes());
    os.flush();

    socket.startHandshake();

    try {
        os.write("Host: localhost\n\n".getBytes());
    } catch (IOException ex) {
        ex.printStackTrace();
        fail("Re-negotiation failed");
    }

    InputStream is = socket.getInputStream();
    Reader r = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(r);
    String line = br.readLine();
    while (line != null) {
        // For testing System.out.println(line);
        line = br.readLine();
    }
}
 
开发者ID:sunmingshuai,项目名称:apache-tomcat-7.0.73-with-comment,代码行数:46,代码来源:TestSsl.java

示例14: verify

import javax.net.ssl.SSLSocket; //导入方法依赖的package包/类
public final void verify(String host, SSLSocket ssl)
      throws IOException {
    if(host == null) {
        throw new NullPointerException("host to verify is null");
    }

    SSLSession session = ssl.getSession();
    if(session == null) {
        // In our experience this only happens under IBM 1.4.x when
        // spurious (unrelated) certificates show up in the server'
        // chain.  Hopefully this will unearth the real problem:
        InputStream in = ssl.getInputStream();
        in.available();
        /*
          If you're looking at the 2 lines of code above because
          you're running into a problem, you probably have two
          options:

            #1.  Clean up the certificate chain that your server
                 is presenting (e.g. edit "/etc/apache2/server.crt"
                 or wherever it is your server's certificate chain
                 is defined).

                                       OR

            #2.   Upgrade to an IBM 1.5.x or greater JVM, or switch
                  to a non-IBM JVM.
        */

        // If ssl.getInputStream().available() didn't cause an
        // exception, maybe at least now the session is available?
        session = ssl.getSession();
        if(session == null) {
            // If it's still null, probably a startHandshake() will
            // unearth the real problem.
            ssl.startHandshake();

            // Okay, if we still haven't managed to cause an exception,
            // might as well go for the NPE.  Or maybe we're okay now?
            session = ssl.getSession();
        }
    }

    Certificate[] certs = session.getPeerCertificates();
    X509Certificate x509 = (X509Certificate) certs[0];
    verify(host, x509);
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:48,代码来源:AbstractVerifier.java

示例15: verify

import javax.net.ssl.SSLSocket; //导入方法依赖的package包/类
public final void verify(final String host, final SSLSocket ssl)
      throws IOException {
    if(host == null) {
        throw new NullPointerException("host to verify is null");
    }

    SSLSession session = ssl.getSession();
    if(session == null) {
        // In our experience this only happens under IBM 1.4.x when
        // spurious (unrelated) certificates show up in the server'
        // chain.  Hopefully this will unearth the real problem:
        final InputStream in = ssl.getInputStream();
        in.available();
        /*
          If you're looking at the 2 lines of code above because
          you're running into a problem, you probably have two
          options:

            #1.  Clean up the certificate chain that your server
                 is presenting (e.g. edit "/etc/apache2/server.crt"
                 or wherever it is your server's certificate chain
                 is defined).

                                       OR

            #2.   Upgrade to an IBM 1.5.x or greater JVM, or switch
                  to a non-IBM JVM.
        */

        // If ssl.getInputStream().available() didn't cause an
        // exception, maybe at least now the session is available?
        session = ssl.getSession();
        if(session == null) {
            // If it's still null, probably a startHandshake() will
            // unearth the real problem.
            ssl.startHandshake();

            // Okay, if we still haven't managed to cause an exception,
            // might as well go for the NPE.  Or maybe we're okay now?
            session = ssl.getSession();
        }
    }

    final Certificate[] certs = session.getPeerCertificates();
    final X509Certificate x509 = (X509Certificate) certs[0];
    verify(host, x509);
}
 
开发者ID:mozilla-mobile,项目名称:FirefoxData-android,代码行数:48,代码来源:AbstractVerifier.java


注:本文中的javax.net.ssl.SSLSocket.startHandshake方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。