javax.net.ssl.SSLHandshakeException#getCause ( )源码实例Demo

下面列出了javax.net.ssl.SSLHandshakeException#getCause ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

@Test
public void testOr() throws Exception {
  MemorizingTrustManager memo=new MemorizingTrustManager.Builder()
    .saveTo(memoDir, "sekrit".toCharArray())
    .noTOFU()
    .build();

  final TrustManagerBuilder tmb=new TrustManagerBuilder()
    .withConfig(InstrumentationRegistry.getContext(),
      R.xml.okhttp3_selfsigned_debug, false)
    .or()
    .add(memo);

  OkHttp3Integrator.applyTo(tmb, builder);
  OkHttpClient client=builder.build();
  CertificateNotMemorizedException memoEx;

  try {
    client.newCall(buildRequest()).execute();

    throw new AssertionFailedError("Expected SSLHandshakeException, did not get!");
  }
  catch (SSLHandshakeException e) {
    if (e.getCause() instanceof CertificateNotMemorizedException) {
      memoEx=(CertificateNotMemorizedException)e.getCause();
    }
    else {
      throw new AssertionFailedError("Expected CertificateNotMemorizedException, did not get!");
    }
  }

  memo.memorize(memoEx);

  Response response=client.newCall(buildRequest()).execute();
  Assert.assertEquals(getExpectedResponse(), response.body().string());
}
 
@Test
public void testAnd() throws Exception {
  MemorizingTrustManager memo=new MemorizingTrustManager.Builder()
    .saveTo(memoDir, "sekrit".toCharArray())
    .noTOFU()
    .build();

  final TrustManagerBuilder tmb=new TrustManagerBuilder()
    .withConfig(InstrumentationRegistry.getContext(),
      R.xml.okhttp3_selfsigned_debug, true)
    .and()
    .add(memo);

  OkHttp3Integrator.applyTo(tmb, builder);
  OkHttpClient client=builder.build();
  CertificateNotMemorizedException memoEx;

  try {
    client.newCall(buildRequest()).execute();

    throw new AssertionFailedError("Expected SSLHandshakeException, did not get!");
  }
  catch (SSLHandshakeException e) {
    if (e.getCause() instanceof CertificateNotMemorizedException) {
      memoEx=(CertificateNotMemorizedException)e.getCause();
    }
    else {
      throw new AssertionFailedError("Expected CertificateNotMemorizedException, did not get!");
    }
  }

  memo.memorize(memoEx);

  Response response=client.newCall(buildRequest()).execute();
  Assert.assertEquals(getExpectedResponse(), response.body().string());
}
 
@Test
public void testSingleItemPrivate() throws Exception {
  MemorizingTrustManager memo=new MemorizingTrustManager.Builder()
    .saveTo(memoDir, "sekrit".toCharArray())
    .noTOFU()
    .onlySingleItemChains()
    .build();

  final TrustManagerBuilder tmb=new TrustManagerBuilder()
    .withConfig(InstrumentationRegistry.getContext(),
      R.xml.okhttp3_selfsigned_debug, true)
    .and()
    .add(memo);

  OkHttp3Integrator.applyTo(tmb, builder);
  OkHttpClient client=builder.build();
  CertificateNotMemorizedException memoEx;

  try {
    client.newCall(buildRequest()).execute();

    throw new AssertionFailedError("Expected SSLHandshakeException, did not get!");
  }
  catch (SSLHandshakeException e) {
    if (e.getCause() instanceof CertificateNotMemorizedException) {
      memoEx=(CertificateNotMemorizedException)e.getCause();
    }
    else {
      throw new AssertionFailedError("Expected CertificateNotMemorizedException, did not get!");
    }
  }

  memo.memorize(memoEx);

  Response response=client.newCall(buildRequest()).execute();
  Assert.assertEquals(getExpectedResponse(), response.body().string());
}
 
源代码4 项目: TrustKit-Android   文件: SSLSocketFactoryTest.java
@Test
public void testPinnedDomainExpiredChain() throws IOException {
    // Initialize TrustKit
    String serverHostname = "expired.badssl.com";
    TestableTrustKit.initializeWithNetworkSecurityConfiguration(
            InstrumentationRegistry.getInstrumentation().getContext(), mockReporter);

    // Create a TrustKit SocketFactory and ensure the connection fails
    SSLSocketFactory test = TestableTrustKit.getInstance().getSSLSocketFactory(serverHostname);
    boolean didReceiveHandshakeError = false;
    try {
        test.createSocket(serverHostname, 443).getInputStream();
    } catch (SSLHandshakeException e) {
        if ((e.getCause() instanceof CertificateException
                && !(e.getCause().getMessage().startsWith("Pin verification failed")))) {
            didReceiveHandshakeError = true;
        }
    }
    assertTrue(didReceiveHandshakeError);

    if (Build.VERSION.SDK_INT < 17) {
        // TrustKit does not do anything for API level < 17 hence there is no reporting
        return;
    }

    // Ensure the background reporter was called
    verify(mockReporter).pinValidationFailed(
            eq(serverHostname),
            eq(0),
            (List<X509Certificate>) org.mockito.Matchers.isNotNull(),
            (List<X509Certificate>) org.mockito.Matchers.isNotNull(),
            eq(TestableTrustKit.getInstance().getConfiguration().getPolicyForHostname(serverHostname)),
            eq(PinningValidationResult.FAILED_CERTIFICATE_CHAIN_NOT_TRUSTED)
    );
}
 
源代码5 项目: TrustKit-Android   文件: SSLSocketFactoryTest.java
@Test
public void testPinnedDomainWrongHostnameChain() throws IOException {
    // Initialize TrustKit
    String serverHostname = "wrong.host.badssl.com";
    TestableTrustKit.initializeWithNetworkSecurityConfiguration(
            InstrumentationRegistry.getInstrumentation().getContext(), mockReporter);

    // Create a TrustKit SocketFactory and ensure the connection fails
    SSLSocketFactory test = TestableTrustKit.getInstance().getSSLSocketFactory(serverHostname);
    boolean didReceiveHandshakeError = false;
    try {
        test.createSocket(serverHostname, 443).getInputStream();
    } catch (SSLHandshakeException e) {
        if ((e.getCause() instanceof CertificateException
                && !(e.getCause().getMessage().startsWith("Pin verification failed")))) {
            didReceiveHandshakeError = true;
        }
    }
    assertTrue(didReceiveHandshakeError);

    if (Build.VERSION.SDK_INT < 17) {
        // TrustKit does not do anything for API level < 17 hence there is no reporting
        return;
    }

    // Ensure the background reporter was called
    verify(mockReporter).pinValidationFailed(
            eq(serverHostname),
            eq(0),
            (List<X509Certificate>) org.mockito.Matchers.isNotNull(),
            (List<X509Certificate>) org.mockito.Matchers.isNotNull(),
            eq(TestableTrustKit.getInstance().getConfiguration().getPolicyForHostname(serverHostname)),
            eq(PinningValidationResult.FAILED_CERTIFICATE_CHAIN_NOT_TRUSTED)
    );
}
 
源代码6 项目: TrustKit-Android   文件: SSLSocketFactoryTest.java
@Test
public void testPinnedDomainInvalidPin() throws IOException {
    if (Build.VERSION.SDK_INT < 17) {
        // TrustKit does not do anything for API level < 17 hence the connection will succeed
        return;
    }

    String serverHostname = "www.yahoo.com";
    TestableTrustKit.initializeWithNetworkSecurityConfiguration(
            InstrumentationRegistry.getInstrumentation().getContext(), mockReporter);

    // Create a TrustKit SocketFactory and ensure the connection fails
    SSLSocketFactory test = TestableTrustKit.getInstance().getSSLSocketFactory(serverHostname);
    boolean didReceivePinningError = false;
    try {
        test.createSocket(serverHostname, 443).getInputStream();
    } catch (SSLHandshakeException e) {
        if ((e.getCause() instanceof CertificateException
                && (e.getCause().getMessage().startsWith("Pin verification failed")))) {
            didReceivePinningError = true;
        }
    }
    assertTrue(didReceivePinningError);

    // Ensure the background reporter was called
    verify(mockReporter).pinValidationFailed(
            eq(serverHostname),
            eq(0),
            (List<X509Certificate>) org.mockito.Matchers.isNotNull(),
            (List<X509Certificate>) org.mockito.Matchers.isNotNull(),
            eq(TestableTrustKit.getInstance().getConfiguration().getPolicyForHostname(serverHostname)),
            eq(PinningValidationResult.FAILED)
    );
}
 
源代码7 项目: TrustKit-Android   文件: SSLSocketFactoryTest.java
@Test
public void testPinnedDomainUntrustedChainAndPinningNotEnforced() throws IOException {
    String serverHostname = "untrusted-root.badssl.com";
    TestableTrustKit.initializeWithNetworkSecurityConfiguration(
            InstrumentationRegistry.getInstrumentation().getContext(), mockReporter);

    // Create a TrustKit SocketFactory and ensure the connection fails
    SSLSocketFactory test = TestableTrustKit.getInstance().getSSLSocketFactory(serverHostname);
    boolean didReceiveHandshakeError = false;
    try {
        test.createSocket(serverHostname, 443).getInputStream();
    } catch (SSLHandshakeException e) {
        if ((e.getCause() instanceof CertificateException
                && !(e.getCause().getMessage().startsWith("Pin verification failed")))) {
            didReceiveHandshakeError = true;
        }
    }

    // Ensure the SSL handshake failed (but not because of a pinning error)
    assertTrue(didReceiveHandshakeError);

    if (Build.VERSION.SDK_INT < 17) {
        // TrustKit does not do anything for API level < 17 hence there is no reporting
        return;
    }

    // Ensure the background reporter was called
    verify(mockReporter).pinValidationFailed(
            eq(serverHostname),
            eq(0),
            (List<X509Certificate>) org.mockito.Matchers.isNotNull(),
            (List<X509Certificate>) org.mockito.Matchers.isNotNull(),
            eq(TestableTrustKit.getInstance().getConfiguration().getPolicyForHostname(serverHostname)),
            eq(PinningValidationResult.FAILED_CERTIFICATE_CHAIN_NOT_TRUSTED)
    );
}
 
源代码8 项目: TrustKit-Android   文件: SSLSocketFactoryTest.java
@Test
public void testNonPinnedDomainUntrustedRootChain() throws IOException {
    String serverHostname = "www.cacert.org";
    final DomainPinningPolicy domainPolicy = new DomainPinningPolicy.Builder()
            .setHostname("other.domain.com")
            .setShouldEnforcePinning(true)
            .setPublicKeyHashes(new HashSet<String>() {{
                // Wrong pins
                add("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=");
                add("BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB=");
            }}).build();

    TestableTrustKit.init(new HashSet<DomainPinningPolicy>() {{ add(domainPolicy); }},
            InstrumentationRegistry.getInstrumentation().getContext(),
            mockReporter);

    // Create a TrustKit SocketFactory and ensure the connection fails
    // This means that TrustKit does not interfere with default certificate validation
    SSLSocketFactory test = TestableTrustKit.getInstance().getSSLSocketFactory(serverHostname);
    boolean didReceiveHandshakeError = false;
    try {
        test.createSocket(serverHostname, 443).getInputStream();
    } catch (SSLHandshakeException e) {
        if ((e.getCause() instanceof CertificateException
                && !(e.getCause().getMessage().startsWith("Pin verification failed")))) {
            didReceiveHandshakeError = true;
        }
    }
    assertTrue(didReceiveHandshakeError);

    // Ensure the background reporter was NOT called as we only want reports for pinned domains
    verify(mockReporter, never()).pinValidationFailed(
            eq(serverHostname),
            eq(0),
            (List<X509Certificate>) org.mockito.Matchers.isNotNull(),
            (List<X509Certificate>) org.mockito.Matchers.isNotNull(),
            eq(TestableTrustKit.getInstance().getConfiguration().getPolicyForHostname(serverHostname)),
            eq(PinningValidationResult.FAILED)
    );
}
 
@Test
public void testTOFU() throws Exception {
  MemorizingTrustManager memo=new MemorizingTrustManager.Builder()
    .saveTo(memoDir, "sekrit".toCharArray())
    .build();

  final TrustManagerBuilder tmb=new TrustManagerBuilder().add(memo);

  OkHttp3Integrator.applyTo(tmb, builder);
  OkHttpClient client=builder.build();
  Response response=client.newCall(buildRequest()).execute();
  Assert.assertEquals(getExpectedResponse(), response.body().string());

  response=client.newCall(buildRequest()).execute();
  Assert.assertEquals(getExpectedResponse(), response.body().string());

  MemorizingTrustManager memoNoTofu=new MemorizingTrustManager.Builder()
    .saveTo(memoDir, "sekrit".toCharArray())
    .noTOFU()
    .build();
  TrustManagerBuilder tmbNoTofu=new TrustManagerBuilder().add(memoNoTofu);
  OkHttpClient.Builder builderNoTofu=new OkHttpClient.Builder();

  OkHttp3Integrator.applyTo(tmbNoTofu, builderNoTofu);

  OkHttpClient clientNoTofu=builderNoTofu.build();

  response=clientNoTofu.newCall(buildRequest()).execute();
  Assert.assertEquals(getExpectedResponse(), response.body().string());

  memoNoTofu.clearAll(true);
  builderNoTofu=new OkHttpClient.Builder();
  OkHttp3Integrator.applyTo(tmbNoTofu, builderNoTofu);
  clientNoTofu=builderNoTofu.build();

  try {
    clientNoTofu.newCall(buildRequest()).execute();

    throw new AssertionFailedError("Expected SSLHandshakeException, did not get!");
  }
  catch (SSLHandshakeException e) {
    if (!(e.getCause() instanceof CertificateNotMemorizedException)) {
      throw e;
    }
  }
}
 
源代码10 项目: TrustKit-Android   文件: SSLSocketFactoryTest.java
@Test
public void testDebugOverridesInvalidPin() throws IOException, CertificateException {
    if (Build.VERSION.SDK_INT >= 24) {
        // This test will not work when using the Android N XML network policy because we can't
        // dynamically switch overridePins to false (as it is true in the XML policy)
        return;
    }
    if (Build.VERSION.SDK_INT < 17) {
        // TrustKit does not do anything for API level < 17 hence the connection will succeed
        return;
    }

    String serverHostname = "www.cacert.org";
    final DomainPinningPolicy domainPolicy = new DomainPinningPolicy.Builder()
            .setHostname(serverHostname)
            .setShouldEnforcePinning(true)
            .setPublicKeyHashes(new HashSet<String>() {{
                // Wrong pins
                add("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=");
                add("BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB=");
            }}).build();

    // Create a configuration with debug overrides enabled to add the cacert.org CA and to set
    // overridePins to false, making the connection fail
    TestableTrustKit.init(new HashSet<DomainPinningPolicy>() {{ add(domainPolicy); }},
            false,
            new HashSet<Certificate>(){{ add(caCertDotOrgRoot); }},
            InstrumentationRegistry.getInstrumentation().getContext(),
            mockReporter);

    // Create a TrustKit SocketFactory and ensure the connection fails
    // This means that debug-overrides properly enables the supplied debug CA cert but does not
    // disable pinning when overridePins is false
    SSLSocketFactory test = TestableTrustKit.getInstance().getSSLSocketFactory(serverHostname);
    boolean didReceivePinningError = false;
    try {
        test.createSocket(serverHostname, 443).getInputStream();
    } catch (SSLHandshakeException e) {
        if ((e.getCause() instanceof CertificateException
                && (e.getCause().getMessage().startsWith("Pin verification failed")))) {
            didReceivePinningError = true;
        }
    }
    assertTrue(didReceivePinningError);

    // Ensure the background reporter was called
    verify(mockReporter).pinValidationFailed(
            eq(serverHostname),
            eq(0),
            (List<X509Certificate>) org.mockito.Matchers.isNotNull(),
            (List<X509Certificate>) org.mockito.Matchers.isNotNull(),
            eq(TestableTrustKit.getInstance().getConfiguration().getPolicyForHostname(serverHostname)),
            eq(PinningValidationResult.FAILED)
    );
}
 
 同类方法