Java 类javax.net.ssl.SSLHandshakeException 实例源码

项目:hadoop-oss    文件:TestSSLHttpServer.java   
/**
 * Test that verifies that excluded ciphers (SSL_RSA_WITH_RC4_128_SHA,
 * TLS_ECDH_ECDSA_WITH_RC4_128_SHA,TLS_ECDH_RSA_WITH_RC4_128_SHA,
 * TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,TLS_ECDHE_RSA_WITH_RC4_128_SHA) are not
 * available for negotiation during SSL connection.
 */
@Test
public void testExcludedCiphers() throws Exception {
  URL url = new URL(baseUrl, "/echo?a=b&c=d");
  HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
  SSLSocketFactory sslSocketF = clientSslFactory.createSSLSocketFactory();
  PrefferedCipherSSLSocketFactory testPreferredCipherSSLSocketF
      = new PrefferedCipherSSLSocketFactory(sslSocketF,
          excludeCiphers.split(","));
  conn.setSSLSocketFactory(testPreferredCipherSSLSocketF);
  assertFalse("excludedCipher list is empty", excludeCiphers.isEmpty());
  try {
    InputStream in = conn.getInputStream();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    IOUtils.copyBytes(in, out, 1024);
    fail("No Ciphers in common, SSLHandshake must fail.");
  } catch (SSLHandshakeException ex) {
    LOG.info("No Ciphers in common, expected succesful test result.", ex);
  }
}
项目:hadoop-oss    文件:TestSSLHttpServer.java   
/** Test that verified that additionally included cipher
 * TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA is only available cipher for working
 * TLS connection from client to server disabled for all other common ciphers.
 */
@Test
public void testOneEnabledCiphers() throws Exception {
  URL url = new URL(baseUrl, "/echo?a=b&c=d");
  HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
  SSLSocketFactory sslSocketF = clientSslFactory.createSSLSocketFactory();
  PrefferedCipherSSLSocketFactory testPreferredCipherSSLSocketF
      = new PrefferedCipherSSLSocketFactory(sslSocketF,
          oneEnabledCiphers.split(","));
  conn.setSSLSocketFactory(testPreferredCipherSSLSocketF);
  assertFalse("excludedCipher list is empty", oneEnabledCiphers.isEmpty());
  try {
    InputStream in = conn.getInputStream();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    IOUtils.copyBytes(in, out, 1024);
    assertEquals(out.toString(), "a:b\nc:d\n");
    LOG.info("Atleast one additional enabled cipher than excluded ciphers,"
        + " expected successful test result.");
  } catch (SSLHandshakeException ex) {
    fail("Atleast one additional cipher available for successful handshake."
        + " Unexpected test failure: " + ex);
  }
}
项目:dtsopensource    文件:HttpProtocolParent.java   
@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
    if (executionCount >= 5) {// 如果已经重试了5次,就放弃
        return false;
    }
    if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试
        return true;
    }
    if (exception instanceof InterruptedIOException) {// 超时
        return false;
    }
    if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常
        return false;
    }
    if (exception instanceof UnknownHostException) {// 目标服务器不可达
        return false;
    }
    if (exception instanceof ConnectTimeoutException) {// 连接被拒绝
        return false;
    }
    if (exception instanceof SSLException) {// SSL握手异常
        return false;
    }
    HttpClientContext clientContext = HttpClientContext.adapt(context);
    HttpRequest request = clientContext.getRequest();
    // 如果请求是幂等的,就再次尝试
    if (!(request instanceof HttpEntityEnclosingRequest)) {
        return true;
    }
    return false;
}
项目:http-fetcher    文件:SimpleHttpFetcher.java   
@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Decide about retry #" + executionCount + " for exception " + exception.getMessage());
    }

    if (executionCount >= _maxRetryCount) {
        // Do not retry if over max retry count
        return false;
    } else if (exception instanceof NoHttpResponseException) {
        // Retry if the server dropped connection on us
        return true;
    } else if (exception instanceof SSLHandshakeException) {
        // Do not retry on SSL handshake exception
        return false;
    }

    HttpRequest request = (HttpRequest) context.getAttribute(HttpCoreContext.HTTP_REQUEST);
    boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
    // Retry if the request is considered idempotent
    return idempotent;
}
项目:hadoop-oss    文件:TestSSLHttpServer.java   
/** Test verifies that mutually exclusive server's disabled cipher suites and
 * client's enabled cipher suites can successfully establish TLS connection.
 */
@Test
public void testExclusiveEnabledCiphers() throws Exception {
  URL url = new URL(baseUrl, "/echo?a=b&c=d");
  HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
  SSLSocketFactory sslSocketF = clientSslFactory.createSSLSocketFactory();
  PrefferedCipherSSLSocketFactory testPreferredCipherSSLSocketF
      = new PrefferedCipherSSLSocketFactory(sslSocketF,
          exclusiveEnabledCiphers.split(","));
  conn.setSSLSocketFactory(testPreferredCipherSSLSocketF);
  assertFalse("excludedCipher list is empty",
      exclusiveEnabledCiphers.isEmpty());
  try {
    InputStream in = conn.getInputStream();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    IOUtils.copyBytes(in, out, 1024);
    assertEquals(out.toString(), "a:b\nc:d\n");
    LOG.info("Atleast one additional enabled cipher than excluded ciphers,"
        + " expected successful test result.");
  } catch (SSLHandshakeException ex) {
    fail("Atleast one additional cipher available for successful handshake."
        + " Unexpected test failure: " + ex);
  }
}
项目:My-Android-Base-Code    文件:ErrorUtils.java   
public void checkError(Throwable e){
    try {
        throwable = e;
        fireBaseReportError(e);
        Crashlytics.logException(e);
        e.printStackTrace();

        if (e instanceof HttpException) {
            int code = getHttpErrorCode(e);
            httpMessage(code);
        }
        else if (e instanceof ConnectException) {
            showToast(mContext.getString(R.string.slow_internet));
        } else if (e instanceof UnknownHostException || e instanceof SocketTimeoutException) {
            showToast(mContext.getString(R.string.internet_not_connected));
        } else if (e instanceof SSLHandshakeException || e instanceof SSLPeerUnverifiedException) {
            showToast(mContext.getString(R.string.server_problem));
        } else {
            showToast(mContext.getString(R.string.unknown_error_msg));
        }
    }
    catch (Exception err){
        err.printStackTrace();
    }
}
项目:hekate    文件:InvalidSslConfigurationTest.java   
@Test
public void testInvalidCertificate() throws Exception {
    NetworkServer server = createServer();

    get(server.start(newServerAddress()));

    NetworkSslConfig ssl = new NetworkSslConfig()
        .withProvider(context().ssl().get().getProvider())
        .withKeyStorePath("ssl/hekate-test2.jks")
        .withKeyStorePassword("hekate-test2")
        .withTrustStorePath("ssl/hekate-test2.jks")
        .withTrustStorePassword("hekate-test2");

    NetworkClient<String> client = createClient(cfg ->
        cfg.setSsl(NettySslUtils.clientContext(ssl, context().resources()))
    );

    try {
        client.connect(server.address(), new NetworkClientCallbackMock<>()).get();

        fail("Error was expected.");
    } catch (ExecutionException e) {
        assertTrue(getStacktrace(e), ErrorUtils.isCausedBy(SSLHandshakeException.class, e));
    }
}
项目:NetDiscovery    文件:RetryHandler.java   
@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {

    if (executionCount >= 3) {// 如果已经重试了3次,就放弃
        return false;
    }

    if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试
        return true;
    }

    if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常
        return false;
    }

    if (exception instanceof InterruptedIOException) {// 超时
        return true;
    }

    if (exception instanceof UnknownHostException) {// 目标服务器不可达
        return false;
    }

    if (exception instanceof ConnectTimeoutException) {// 连接被拒绝
        return false;
    }

    if (exception instanceof SSLException) {// ssl握手异常
        return false;
    }

    HttpClientContext clientContext = HttpClientContext.adapt(context);
    HttpRequest request = clientContext.getRequest();

    // 如果请求是幂等的,就再次尝试
    if (!(request instanceof HttpEntityEnclosingRequest)) {
        return true;
    }
    return false;
}
项目:PicCrawler    文件:RetryHandler.java   
@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {

    if (executionCount >= 3) {// 如果已经重试了3次,就放弃
        return false;
    }

    if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试
        return true;
    }

    if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常
        return false;
    }

    if (exception instanceof InterruptedIOException) {// 超时
        return true;
    }

    if (exception instanceof UnknownHostException) {// 目标服务器不可达
        return false;
    }

    if (exception instanceof ConnectTimeoutException) {// 连接被拒绝
        return false;
    }

    if (exception instanceof SSLException) {// ssl握手异常
        return false;
    }

    HttpClientContext clientContext = HttpClientContext.adapt(context);
    HttpRequest request = clientContext.getRequest();

    // 如果请求是幂等的,就再次尝试
    if (!(request instanceof HttpEntityEnclosingRequest)) {
        return true;
    }
    return false;
}
项目:OpenJSharp    文件:JConsole.java   
private String errorMessage(Exception ex) {
   String msg = Messages.CONNECTION_FAILED;
   if (ex instanceof IOException || ex instanceof SecurityException) {
       Throwable cause = null;
       Throwable c = ex.getCause();
       while (c != null) {
           cause = c;
           c = c.getCause();
       }
       if (cause instanceof ConnectException) {
           return msg + ": " + cause.getMessage();
       } else if (cause instanceof UnknownHostException) {
           return Resources.format(Messages.UNKNOWN_HOST, cause.getMessage());
       } else if (cause instanceof NoRouteToHostException) {
           return msg + ": " + cause.getMessage();
       } else if (cause instanceof FailedLoginException) {
           return msg + ": " + cause.getMessage();
       } else if (cause instanceof SSLHandshakeException) {
           return msg + ": "+ cause.getMessage();
       }
    } else if (ex instanceof MalformedURLException) {
       return Resources.format(Messages.INVALID_URL, ex.getMessage());
    }
    return msg + ": " + ex.getMessage();
}
项目:ProxyPool    文件:RetryHandler.java   
@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {

    if (executionCount >= 3) {// 如果已经重试了3次,就放弃
        return false;
    }

    if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试
        return true;
    }

    if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常
        return false;
    }

    if (exception instanceof InterruptedIOException) {// 超时
        return true;
    }

    if (exception instanceof UnknownHostException) {// 目标服务器不可达
        return false;
    }

    if (exception instanceof ConnectTimeoutException) {// 连接被拒绝
        return false;
    }

    if (exception instanceof SSLException) {// ssl握手异常
        return false;
    }

    HttpClientContext clientContext = HttpClientContext.adapt(context);
    HttpRequest request = clientContext.getRequest();

    // 如果请求是幂等的,就再次尝试
    if (!(request instanceof HttpEntityEnclosingRequest)) {
        return true;
    }
    return false;
}
项目:jdk8u-jdk    文件:DHCrypt.java   
void checkConstraints(AlgorithmConstraints constraints,
        BigInteger peerPublicValue) throws SSLHandshakeException {

    try {
        KeyFactory kf = JsseJce.getKeyFactory("DiffieHellman");
        DHPublicKeySpec spec =
                    new DHPublicKeySpec(peerPublicValue, modulus, base);
        DHPublicKey publicKey = (DHPublicKey)kf.generatePublic(spec);

        // check constraints of DHPublicKey
        if (!constraints.permits(
                EnumSet.of(CryptoPrimitive.KEY_AGREEMENT), publicKey)) {
            throw new SSLHandshakeException(
                "DHPublicKey does not comply to algorithm constraints");
        }
    } catch (GeneralSecurityException gse) {
        throw (SSLHandshakeException) new SSLHandshakeException(
                "Could not generate DHPublicKey").initCause(gse);
    }
}
项目:jdk8u-jdk    文件:ECDHCrypt.java   
SecretKey getAgreedSecret(
        byte[] encodedPoint) throws SSLHandshakeException {

    try {
        ECParameterSpec params = publicKey.getParams();
        ECPoint point =
                JsseJce.decodePoint(encodedPoint, params.getCurve());
        KeyFactory kf = JsseJce.getKeyFactory("EC");
        ECPublicKeySpec spec = new ECPublicKeySpec(point, params);
        PublicKey peerPublicKey = kf.generatePublic(spec);
        return getAgreedSecret(peerPublicKey);
    } catch (GeneralSecurityException | java.io.IOException e) {
        throw (SSLHandshakeException) new SSLHandshakeException(
            "Could not generate secret").initCause(e);
    }
}
项目:jdk8u-jdk    文件:JConsole.java   
private String errorMessage(Exception ex) {
   String msg = Messages.CONNECTION_FAILED;
   if (ex instanceof IOException || ex instanceof SecurityException) {
       Throwable cause = null;
       Throwable c = ex.getCause();
       while (c != null) {
           cause = c;
           c = c.getCause();
       }
       if (cause instanceof ConnectException) {
           return msg + ": " + cause.getMessage();
       } else if (cause instanceof UnknownHostException) {
           return Resources.format(Messages.UNKNOWN_HOST, cause.getMessage());
       } else if (cause instanceof NoRouteToHostException) {
           return msg + ": " + cause.getMessage();
       } else if (cause instanceof FailedLoginException) {
           return msg + ": " + cause.getMessage();
       } else if (cause instanceof SSLHandshakeException) {
           return msg + ": "+ cause.getMessage();
       }
    } else if (ex instanceof MalformedURLException) {
       return Resources.format(Messages.INVALID_URL, ex.getMessage());
    }
    return msg + ": " + ex.getMessage();
}
项目:jdk8u-jdk    文件:JMXStartStopTest.java   
private static void testNoConnect(int port, int rmiPort) throws Exception {
    try {
        testConnect(port, rmiPort);
        throw new Exception("Didn't expect the management agent running");
    } catch (Exception e) {
        Throwable t = e;
        while (t != null) {
            if (t instanceof NoSuchObjectException ||
                t instanceof ConnectException ||
                t instanceof SSLHandshakeException) {
                break;
            }
            t = t.getCause();
        }
        if (t == null) {
            throw new Exception("Unexpected exception", e);
        }
    }
}
项目:openjdk-jdk10    文件:DHCrypt.java   
void checkConstraints(AlgorithmConstraints constraints,
        BigInteger peerPublicValue) throws SSLHandshakeException {

    try {
        KeyFactory kf = JsseJce.getKeyFactory("DiffieHellman");
        DHPublicKeySpec spec =
                    new DHPublicKeySpec(peerPublicValue, modulus, base);
        DHPublicKey publicKey = (DHPublicKey)kf.generatePublic(spec);

        // check constraints of DHPublicKey
        if (!constraints.permits(
                EnumSet.of(CryptoPrimitive.KEY_AGREEMENT), publicKey)) {
            throw new SSLHandshakeException(
                "DHPublicKey does not comply to algorithm constraints");
        }
    } catch (GeneralSecurityException gse) {
        throw (SSLHandshakeException) new SSLHandshakeException(
                "Could not generate DHPublicKey").initCause(gse);
    }
}
项目:openjdk-jdk10    文件:ECDHCrypt.java   
SecretKey getAgreedSecret(
        byte[] encodedPoint) throws SSLHandshakeException {

    try {
        ECParameterSpec params = publicKey.getParams();
        ECPoint point =
                JsseJce.decodePoint(encodedPoint, params.getCurve());
        KeyFactory kf = JsseJce.getKeyFactory("EC");
        ECPublicKeySpec spec = new ECPublicKeySpec(point, params);
        PublicKey peerPublicKey = kf.generatePublic(spec);
        return getAgreedSecret(peerPublicKey);
    } catch (GeneralSecurityException | java.io.IOException e) {
        throw (SSLHandshakeException) new SSLHandshakeException(
            "Could not generate secret").initCause(e);
    }
}
项目:openjdk-jdk10    文件:JConsole.java   
private String errorMessage(Exception ex) {
   String msg = Messages.CONNECTION_FAILED;
   if (ex instanceof IOException || ex instanceof SecurityException) {
       Throwable cause = null;
       Throwable c = ex.getCause();
       while (c != null) {
           cause = c;
           c = c.getCause();
       }
       if (cause instanceof ConnectException) {
           return msg + ": " + cause.getMessage();
       } else if (cause instanceof UnknownHostException) {
           return Resources.format(Messages.UNKNOWN_HOST, cause.getMessage());
       } else if (cause instanceof NoRouteToHostException) {
           return msg + ": " + cause.getMessage();
       } else if (cause instanceof FailedLoginException) {
           return msg + ": " + cause.getMessage();
       } else if (cause instanceof SSLHandshakeException) {
           return msg + ": "+ cause.getMessage();
       }
    } else if (ex instanceof MalformedURLException) {
       return Resources.format(Messages.INVALID_URL, ex.getMessage());
    }
    return msg + ": " + ex.getMessage();
}
项目:openjdk-jdk10    文件:JMXStartStopTest.java   
private static void testNoConnect(int port, int rmiPort) throws Exception {
    try {
        testConnect(port, rmiPort);
        throw new Exception("Didn't expect the management agent running");
    } catch (Exception e) {
        Throwable t = e;
        while (t != null) {
            if (t instanceof RemoteException ||
                t instanceof SSLHandshakeException ||
                t instanceof ConnectException) {
                break;
            }
            t = t.getCause();
        }
        if (t == null) {
            throw new Exception("Unexpected exception", e);
        }
    }
}
项目:openjdk9    文件:DHCrypt.java   
void checkConstraints(AlgorithmConstraints constraints,
        BigInteger peerPublicValue) throws SSLHandshakeException {

    try {
        KeyFactory kf = JsseJce.getKeyFactory("DiffieHellman");
        DHPublicKeySpec spec =
                    new DHPublicKeySpec(peerPublicValue, modulus, base);
        DHPublicKey publicKey = (DHPublicKey)kf.generatePublic(spec);

        // check constraints of DHPublicKey
        if (!constraints.permits(
                EnumSet.of(CryptoPrimitive.KEY_AGREEMENT), publicKey)) {
            throw new SSLHandshakeException(
                "DHPublicKey does not comply to algorithm constraints");
        }
    } catch (GeneralSecurityException gse) {
        throw (SSLHandshakeException) new SSLHandshakeException(
                "Could not generate DHPublicKey").initCause(gse);
    }
}
项目:openjdk9    文件:ECDHCrypt.java   
SecretKey getAgreedSecret(
        byte[] encodedPoint) throws SSLHandshakeException {

    try {
        ECParameterSpec params = publicKey.getParams();
        ECPoint point =
                JsseJce.decodePoint(encodedPoint, params.getCurve());
        KeyFactory kf = JsseJce.getKeyFactory("EC");
        ECPublicKeySpec spec = new ECPublicKeySpec(point, params);
        PublicKey peerPublicKey = kf.generatePublic(spec);
        return getAgreedSecret(peerPublicKey);
    } catch (GeneralSecurityException | java.io.IOException e) {
        throw (SSLHandshakeException) new SSLHandshakeException(
            "Could not generate secret").initCause(e);
    }
}
项目:openjdk9    文件:JConsole.java   
private String errorMessage(Exception ex) {
   String msg = Messages.CONNECTION_FAILED;
   if (ex instanceof IOException || ex instanceof SecurityException) {
       Throwable cause = null;
       Throwable c = ex.getCause();
       while (c != null) {
           cause = c;
           c = c.getCause();
       }
       if (cause instanceof ConnectException) {
           return msg + ": " + cause.getMessage();
       } else if (cause instanceof UnknownHostException) {
           return Resources.format(Messages.UNKNOWN_HOST, cause.getMessage());
       } else if (cause instanceof NoRouteToHostException) {
           return msg + ": " + cause.getMessage();
       } else if (cause instanceof FailedLoginException) {
           return msg + ": " + cause.getMessage();
       } else if (cause instanceof SSLHandshakeException) {
           return msg + ": "+ cause.getMessage();
       }
    } else if (ex instanceof MalformedURLException) {
       return Resources.format(Messages.INVALID_URL, ex.getMessage());
    }
    return msg + ": " + ex.getMessage();
}
项目:openjdk9    文件:JMXStartStopTest.java   
private static void testNoConnect(int port, int rmiPort) throws Exception {
    try {
        testConnect(port, rmiPort);
        throw new Exception("Didn't expect the management agent running");
    } catch (Exception e) {
        Throwable t = e;
        while (t != null) {
            if (t instanceof RemoteException ||
                t instanceof SSLHandshakeException ||
                t instanceof ConnectException) {
                break;
            }
            t = t.getCause();
        }
        if (t == null) {
            throw new Exception("Unexpected exception", e);
        }
    }
}
项目:helium    文件:BaseTest.java   
protected byte[] downloadFile(String xpath, String fitxer) {

    //System.setProperty ("jsse.enableSNIExtension", "false");

    FileDownloader downloader = new FileDownloader(driver);
    driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
    boolean isPresent = driver.findElements(By.xpath(xpath)).size() > 0;
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    assertTrue("Enllaç al fitxer " + fitxer + " no existeix" , isPresent);

    byte[] downloadedFile = null;

    try {
        downloadedFile = downloader.downloadFile(driver.findElement(By.xpath(xpath)));
    } catch (SSLHandshakeException certEx) {
        certEx.printStackTrace();
        fail("No s'ha pogut descarregar el fitxer " + fitxer + ". Error de certificat.");
    } catch (Exception e) {
        e.printStackTrace();
        fail("No s'ha pogut descarregar el fitxer " + fitxer);
    }

    assertThat(downloader.getHTTPStatusOfLastDownloadAttempt(), is(equalTo(200)));

    return downloadedFile;
}
项目:zapp    文件:MediathekListFragment.java   
@Override
public void onFailure(@NonNull Call<MediathekAnswer> call, @NonNull Throwable t) {
    adapter.setLoading(false);
    swipeRefreshLayout.setRefreshing(false);

    if (!call.isCanceled()) {
        // ignore canceled calls, because it most likely was canceled by app code
        Timber.e(t);

        if (t instanceof SSLHandshakeException || t instanceof UnknownServiceException) {
            showError(R.string.error_mediathek_ssl_error);
        } else {
            showError(R.string.error_mediathek_info_not_available);
        }
    }
}
项目:infoarchive-sip-sdk    文件:WhenMakingHttpCallsUsingApache.java   
@Test
public void shouldAllowCustomProcessingOfResponse() throws IOException {
  String uri = "http://google.com";
  String expected = randomString();
  ResponseFactory<String> responseFactory = (resp, closer) -> {
    return expected;
  };

  try {
    String actual = httpClient.get(uri, Collections.emptyList(), responseFactory);

    assertEquals("Response", expected, actual);
  } catch (HttpException e) {
    Throwable cause = e.getCause();
    if (cause instanceof SSLHandshakeException || cause instanceof UnknownHostException) {
      // This can happen when on a VPN and the company blocks certain TLS traffic
      return;
    }
    throw e;
  }
}
项目:client-java-httpclient-repacked    文件:TestSSLSocketFactory.java   
@Test(expected=SSLHandshakeException.class)
public void testSSLTrustVerification() throws Exception {
    final SSLContext serverSSLContext = SSLContexts.custom()
            .useProtocol("TLS")
            .loadTrustMaterial(keystore)
            .loadKeyMaterial(keystore, "nopassword".toCharArray())
            .build();

    this.localServer = new LocalTestServer(serverSSLContext);
    this.localServer.registerDefaultHandlers();
    this.localServer.start();

    final HttpHost host = new HttpHost("localhost", 443, "https");
    final HttpContext context = new BasicHttpContext();
    // Use default SSL context
    final SSLContext defaultsslcontext = SSLContexts.createDefault();

    final SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(defaultsslcontext,
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    final Socket socket = socketFactory.createSocket(context);
    final InetSocketAddress remoteAddress = this.localServer.getServiceAddress();
    socketFactory.connectSocket(0, socket, host, remoteAddress, null, context);
}
项目:conscrypt    文件:ConscryptSocketTest.java   
@Test
public void test_setEnabledProtocols_FiltersSSLv3_HandshakeException() throws Exception {
    TestConnection connection = new TestConnection(new X509Certificate[] {cert, ca}, certKey);

    connection.clientHooks = new ClientHooks() {
        @Override
        public AbstractConscryptSocket createSocket(ServerSocket listener) throws IOException {
            AbstractConscryptSocket socket = super.createSocket(listener);
            socket.setEnabledProtocols(new String[] {"SSLv3"});
            assertEquals(
                    "SSLv3 should be filtered out", 0, socket.getEnabledProtocols().length);
            return socket;
        }
    };

    connection.doHandshake();
    assertThat(connection.clientException, instanceOf(SSLHandshakeException.class));
    assertTrue(
            connection.clientException.getMessage().contains("SSLv3 is no longer supported"));
    assertThat(connection.serverException, instanceOf(SSLHandshakeException.class));

    assertFalse(connection.clientHooks.isHandshakeCompleted);
    assertFalse(connection.serverHooks.isHandshakeCompleted);
}
项目:conscrypt    文件:NativeSsl.java   
private void setTlsChannelId(OpenSSLKey channelIdPrivateKey) throws SSLException {
    if (!parameters.channelIdEnabled) {
        return;
    }

    if (parameters.getUseClientMode()) {
        // Client-side TLS Channel ID
        if (channelIdPrivateKey == null) {
            throw new SSLHandshakeException("Invalid TLS channel ID key specified");
        }
        NativeCrypto.SSL_set1_tls_channel_id(ssl, channelIdPrivateKey.getNativeRef());
    } else {
        // Server-side TLS Channel ID
        NativeCrypto.SSL_enable_tls_channel_id(ssl);
    }
}
项目:conscrypt    文件:SSLEngineTest.java   
@Test
public void test_SSLEngine_beginHandshake_noKeyStore() throws Exception {
    TestSSLContext c = TestSSLContext.newBuilder()
                               .useDefaults(false)
                               .clientContext(SSLContext.getDefault())
                               .serverContext(SSLContext.getDefault())
                               .build();
    SSLEngine[] p = null;
    try {
        // TODO Fix KnownFailure AlertException "NO SERVER CERTIFICATE FOUND"
        // ServerHandshakeImpl.selectSuite should not select a suite without a required cert
        p = TestSSLEnginePair.connect(c, null);
        fail();
    } catch (SSLHandshakeException expected) {
        // Ignored.
    } finally {
        if (p != null) {
            TestSSLEnginePair.close(p);
        }
    }
    c.close();
}
项目:conscrypt    文件:SSLEngineTest.java   
/**
 * http://code.google.com/p/android/issues/detail?id=31903
 * This test case verifies that if the server requires a client cert
 * (setNeedClientAuth) but the client does not provide one SSL connection
 * establishment will fail
 */
@Test
public void test_SSLEngine_clientAuthNeededNoClientCert() throws Exception {
    TestSSLContext clientAuthContext =
            TestSSLContext.create(TestKeyStore.getClient(), TestKeyStore.getServer());
    TestSSLEnginePair p = null;
    try {
        p = TestSSLEnginePair.create(clientAuthContext, new TestSSLEnginePair.Hooks() {
            @Override
            void beforeBeginHandshake(SSLEngine client, SSLEngine server) {
                server.setNeedClientAuth(true);
            }
        });
        fail();
    } catch (SSLHandshakeException expected) {
        // Ignored.
    } finally {
        clientAuthContext.close();
        if (p != null) {
            p.close();
        }
    }
}
项目:vespa    文件:HTTPSearcher.java   
@Override
public boolean retryRequest(IOException e, int executionCount, HttpContext httpContext) {
    if (e == null) {
        throw new IllegalArgumentException("Exception parameter may not be null");
    }
    if (executionCount > retries) {
        return false;
    }
    if (e instanceof NoHttpResponseException) {
        // Retry if the server dropped connection on us
        return true;
    }
    if (e instanceof InterruptedIOException) {
        // Timeout from federation layer
        return false;
    }
    if (e instanceof UnknownHostException) {
        // Unknown host
        return false;
    }
    if (e instanceof SSLHandshakeException) {
        // SSL handshake exception
        return false;
    }
    return true;
}
项目:cloud-sql-jdbc-socket-factory    文件:SslSocketFactory.java   
public Socket create(String instanceName) throws IOException {
  try {
    return createAndConfigureSocket(instanceName, CertificateCaching.USE_CACHE);
  } catch (SSLHandshakeException e) {
    logger.warning(
        String.format(
            "SSL handshake failed for Cloud SQL instance [%s], "
                + "retrying with new certificate.\n%s",
            instanceName,
            Throwables.getStackTraceAsString(e)));

    if (!forcedRenewRateLimiter.tryAcquire()) {
      logger.warning(
          String.format(
              "Renewing too often, rate limiting certificate renewal for Cloud SQL "
                  + "instance [%s].",
              instanceName));
      forcedRenewRateLimiter.acquire();
    }
    return createAndConfigureSocket(instanceName, CertificateCaching.BYPASS_CACHE);
  }
}
项目:jdk8u_jdk    文件:ECDHCrypt.java   
SecretKey getAgreedSecret(
        byte[] encodedPoint) throws SSLHandshakeException {

    try {
        ECParameterSpec params = publicKey.getParams();
        ECPoint point =
                JsseJce.decodePoint(encodedPoint, params.getCurve());
        KeyFactory kf = JsseJce.getKeyFactory("EC");
        ECPublicKeySpec spec = new ECPublicKeySpec(point, params);
        PublicKey peerPublicKey = kf.generatePublic(spec);
        return getAgreedSecret(peerPublicKey);
    } catch (GeneralSecurityException | java.io.IOException e) {
        throw (SSLHandshakeException) new SSLHandshakeException(
            "Could not generate secret").initCause(e);
    }
}
项目:jdk8u_jdk    文件:JConsole.java   
private String errorMessage(Exception ex) {
   String msg = Messages.CONNECTION_FAILED;
   if (ex instanceof IOException || ex instanceof SecurityException) {
       Throwable cause = null;
       Throwable c = ex.getCause();
       while (c != null) {
           cause = c;
           c = c.getCause();
       }
       if (cause instanceof ConnectException) {
           return msg + ": " + cause.getMessage();
       } else if (cause instanceof UnknownHostException) {
           return Resources.format(Messages.UNKNOWN_HOST, cause.getMessage());
       } else if (cause instanceof NoRouteToHostException) {
           return msg + ": " + cause.getMessage();
       } else if (cause instanceof FailedLoginException) {
           return msg + ": " + cause.getMessage();
       } else if (cause instanceof SSLHandshakeException) {
           return msg + ": "+ cause.getMessage();
       }
    } else if (ex instanceof MalformedURLException) {
       return Resources.format(Messages.INVALID_URL, ex.getMessage());
    }
    return msg + ": " + ex.getMessage();
}
项目:jdk8u_jdk    文件:JMXStartStopTest.java   
private static void testNoConnect(int port, int rmiPort) throws Exception {
    try {
        testConnect(port, rmiPort);
        throw new Exception("Didn't expect the management agent running");
    } catch (Exception e) {
        Throwable t = e;
        while (t != null) {
            if (t instanceof NoSuchObjectException ||
                t instanceof ConnectException ||
                t instanceof SSLHandshakeException) {
                break;
            }
            t = t.getCause();
        }
        if (t == null) {
            throw new Exception("Unexpected exception", e);
        }
    }
}
项目:lookaside_java-1.8.0-openjdk    文件:DHCrypt.java   
void checkConstraints(AlgorithmConstraints constraints,
        BigInteger peerPublicValue) throws SSLHandshakeException {

    try {
        KeyFactory kf = JsseJce.getKeyFactory("DiffieHellman");
        DHPublicKeySpec spec =
                    new DHPublicKeySpec(peerPublicValue, modulus, base);
        DHPublicKey publicKey = (DHPublicKey)kf.generatePublic(spec);

        // check constraints of DHPublicKey
        if (!constraints.permits(
                EnumSet.of(CryptoPrimitive.KEY_AGREEMENT), publicKey)) {
            throw new SSLHandshakeException(
                "DHPublicKey does not comply to algorithm constraints");
        }
    } catch (GeneralSecurityException gse) {
        throw (SSLHandshakeException) new SSLHandshakeException(
                "Could not generate DHPublicKey").initCause(gse);
    }
}
项目:lookaside_java-1.8.0-openjdk    文件:ECDHCrypt.java   
SecretKey getAgreedSecret(
        byte[] encodedPoint) throws SSLHandshakeException {

    try {
        ECParameterSpec params = publicKey.getParams();
        ECPoint point =
                JsseJce.decodePoint(encodedPoint, params.getCurve());
        KeyFactory kf = JsseJce.getKeyFactory("EC");
        ECPublicKeySpec spec = new ECPublicKeySpec(point, params);
        PublicKey peerPublicKey = kf.generatePublic(spec);
        return getAgreedSecret(peerPublicKey);
    } catch (GeneralSecurityException | java.io.IOException e) {
        throw (SSLHandshakeException) new SSLHandshakeException(
            "Could not generate secret").initCause(e);
    }
}
项目:lookaside_java-1.8.0-openjdk    文件:JConsole.java   
private String errorMessage(Exception ex) {
   String msg = Messages.CONNECTION_FAILED;
   if (ex instanceof IOException || ex instanceof SecurityException) {
       Throwable cause = null;
       Throwable c = ex.getCause();
       while (c != null) {
           cause = c;
           c = c.getCause();
       }
       if (cause instanceof ConnectException) {
           return msg + ": " + cause.getMessage();
       } else if (cause instanceof UnknownHostException) {
           return Resources.format(Messages.UNKNOWN_HOST, cause.getMessage());
       } else if (cause instanceof NoRouteToHostException) {
           return msg + ": " + cause.getMessage();
       } else if (cause instanceof FailedLoginException) {
           return msg + ": " + cause.getMessage();
       } else if (cause instanceof SSLHandshakeException) {
           return msg + ": "+ cause.getMessage();
       }
    } else if (ex instanceof MalformedURLException) {
       return Resources.format(Messages.INVALID_URL, ex.getMessage());
    }
    return msg + ": " + ex.getMessage();
}
项目:lookaside_java-1.8.0-openjdk    文件:JMXStartStopTest.java   
private static void testNoConnect(int port, int rmiPort) throws Exception {
    try {
        testConnect(port, rmiPort);
        throw new Exception("Didn't expect the management agent running");
    } catch (Exception e) {
        Throwable t = e;
        while (t != null) {
            if (t instanceof NoSuchObjectException ||
                t instanceof ConnectException ||
                t instanceof SSLHandshakeException) {
                break;
            }
            t = t.getCause();
        }
        if (t == null) {
            throw new Exception("Unexpected exception", e);
        }
    }
}