Java Code Examples for javax.net.ssl.X509TrustManager

The following are top voted examples for showing how to use javax.net.ssl.X509TrustManager. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: q-mail   File: TrustManagerFactoryTest.java   View source code 8 votes vote down vote up
@Test
public void testLocallyTrustedCertificateChain() throws Exception {
    mKeyStore.addCertificate(MATCHING_HOST, PORT1, mCert3);

    X509TrustManager trustManager = TrustManagerFactory.get(MATCHING_HOST, PORT1);
    trustManager.checkServerTrusted(new X509Certificate[] { mCert3, mCaCert }, "authType");
}
 
Example 2
Project: the-vigilantes   File: ExportControlled.java   View source code 7 votes vote down vote up
public X509TrustManagerWrapper(X509TrustManager tm, boolean verifyServerCertificate) throws CertificateException {
    this.origTm = tm;
    this.verifyServerCert = verifyServerCertificate;

    if (verifyServerCertificate) {
        try {
            Set<TrustAnchor> anch = new HashSet<TrustAnchor>();
            for (X509Certificate cert : tm.getAcceptedIssuers()) {
                anch.add(new TrustAnchor(cert, null));
            }
            this.validatorParams = new PKIXParameters(anch);
            this.validatorParams.setRevocationEnabled(false);
            this.validator = CertPathValidator.getInstance("PKIX");
            this.certFactory = CertificateFactory.getInstance("X.509");
        } catch (Exception e) {
            throw new CertificateException(e);
        }
    }
}
 
Example 3
Project: Android_Code_Arbiter   File: KeyStoresTrustManager.java   View source code 6 votes vote down vote up
@Override
public void checkServerTrusted(X509Certificate[] certificates, String authType) throws CertificateException {
    CertificateException catchException = null;
    for (X509TrustManager tm : trustManagers) {
        try {
            tm.checkServerTrusted(certificates, authType);
            return;
        } catch (CertificateException e) {
            catchException = e;
        }
    }
    throw catchException;
}
 
Example 4
Project: outland   File: CertificateLoader.java   View source code 6 votes vote down vote up
private void create(Path path)
    throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException,
    KeyManagementException {
  TrustManager[] trustManagers;
  KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
  keyStore.load(null, null);

  installCertificates(path, keyStore);

  String defaultAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
  TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(defaultAlgorithm);
  trustManagerFactory.init(keyStore);
  trustManagers = trustManagerFactory.getTrustManagers();
  sslContext = SSLContext.getInstance("TLS");
  sslContext.init(null, trustManagers, null);
  trustManager = (X509TrustManager) trustManagers[0];
  X509Certificate[] acceptedIssuers = trustManager.getAcceptedIssuers();
  for (X509Certificate acceptedIssuer : acceptedIssuers) {
    logger.info("installed cert details: subject={} issuer={}",
        acceptedIssuer.getSubjectX500Principal(), acceptedIssuer.getIssuerX500Principal());
  }
}
 
Example 5
Project: OpenVertretung   File: ExportControlled.java   View source code 6 votes vote down vote up
public X509TrustManagerWrapper(X509TrustManager tm, boolean verifyServerCertificate) throws CertificateException {
    this.origTm = tm;
    this.verifyServerCert = verifyServerCertificate;

    if (verifyServerCertificate) {
        try {
            Set<TrustAnchor> anch = new HashSet<TrustAnchor>();
            for (X509Certificate cert : tm.getAcceptedIssuers()) {
                anch.add(new TrustAnchor(cert, null));
            }
            this.validatorParams = new PKIXParameters(anch);
            this.validatorParams.setRevocationEnabled(false);
            this.validator = CertPathValidator.getInstance("PKIX");
            this.certFactory = CertificateFactory.getInstance("X.509");
        } catch (Exception e) {
            throw new CertificateException(e);
        }
    }
}
 
Example 6
Project: GitHub   File: Main.java   View source code 6 votes vote down vote up
private OkHttpClient createClient() {
  OkHttpClient.Builder builder = new OkHttpClient.Builder();
  builder.followSslRedirects(followRedirects);
  if (connectTimeout != DEFAULT_TIMEOUT) {
    builder.connectTimeout(connectTimeout, SECONDS);
  }
  if (readTimeout != DEFAULT_TIMEOUT) {
    builder.readTimeout(readTimeout, SECONDS);
  }
  if (allowInsecure) {
    X509TrustManager trustManager = createInsecureTrustManager();
    SSLSocketFactory sslSocketFactory = createInsecureSslSocketFactory(trustManager);
    builder.sslSocketFactory(sslSocketFactory, trustManager);
    builder.hostnameVerifier(createInsecureHostnameVerifier());
  }
  return builder.build();
}
 
Example 7
Project: dracoon-dropzone   File: RestClient.java   View source code 6 votes vote down vote up
private X509TrustManager getX509TrustManager() {
	try {
		TrustManagerFactory trustManagerFactory = TrustManagerFactory
				.getInstance(TrustManagerFactory.getDefaultAlgorithm());
		trustManagerFactory.init((KeyStore) null);
		TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
		if (trustManagers.length == 1 && (trustManagers[0] instanceof X509TrustManager)) {
			return (X509TrustManager) trustManagers[0];
		} else {
			LOG.error(String.format("Error while retrieving X509 trust manager! " + "(TrustMangers: %s)",
					Arrays.toString(trustManagers)));
			return null;
		}
	} catch (NoSuchAlgorithmException | KeyStoreException e) {
		LOG.error("Error while retrieving X509 trust manager!", e);
		return null;
	}
}
 
Example 8
Project: springboot-shiro-cas-mybatis   File: FileTrustStoreSslSocketFactory.java   View source code 6 votes vote down vote up
@Override
public void checkClientTrusted(final X509Certificate[] chain, final String authType) throws CertificateException {
    for (final X509TrustManager trustManager : trustManagers) {
        try {
            trustManager.checkClientTrusted(chain, authType);
            return;
        } catch (final CertificateException e) {
            LOGGER.debug(e.getMessage(), e);
        }
    }
    throw new CertificateException("None of the TrustManagers trust this certificate chain");
}
 
Example 9
Project: Android_Code_Arbiter   File: KeyStoresTrustManager.java   View source code 6 votes vote down vote up
public KeyStoresTrustManager(KeyStore... keyStores) throws NoSuchAlgorithmException, KeyStoreException {
    super();

    for (KeyStore keystore : keyStores) {
        TrustManagerFactory factory = TrustManagerFactory.getInstance("JKS");
        factory.init(keystore);
        TrustManager[] tms = factory.getTrustManagers();
        if (tms.length == 0) {
            throw new NoSuchAlgorithmException("Unable to load keystore");
        }
        trustManagers.add((X509TrustManager) tms[0]);
    }

    //Build accepted issuers list
    Set<X509Certificate> issuers = new HashSet<X509Certificate>();
    for (X509TrustManager tm : trustManagers) {
        for (X509Certificate issuer : tm.getAcceptedIssuers()) {
            issuers.add(issuer);
        }
    }
    acceptedIssuers = issuers.toArray(new X509Certificate[issuers.size()]);
}
 
Example 10
Project: ProyectoPacientes   File: ExportControlled.java   View source code 6 votes vote down vote up
public X509TrustManagerWrapper(X509TrustManager tm, boolean verifyServerCertificate) throws CertificateException {
    this.origTm = tm;
    this.verifyServerCert = verifyServerCertificate;

    if (verifyServerCertificate) {
        try {
            Set<TrustAnchor> anch = new HashSet<TrustAnchor>();
            for (X509Certificate cert : tm.getAcceptedIssuers()) {
                anch.add(new TrustAnchor(cert, null));
            }
            this.validatorParams = new PKIXParameters(anch);
            this.validatorParams.setRevocationEnabled(false);
            this.validator = CertPathValidator.getInstance("PKIX");
            this.certFactory = CertificateFactory.getInstance("X.509");
        } catch (Exception e) {
            throw new CertificateException(e);
        }
    }
}
 
Example 11
Project: super-volley   File: SuperVolley.java   View source code 6 votes vote down vote up
private OkHttpClient getDefaultOkHttpClient(boolean isSecured, boolean followRedirects,
                                            boolean followProtocolRedirects, String[] publicKeys,
                                            Collection<Interceptor> interceptors, LogLevel logLevel) {
    ClientSSLSocketFactory.setIsSecured(isSecured);
    ClientSSLSocketFactory.setPublicKeys(publicKeys);
    SSLSocketFactory sslSocketFactory = ClientSSLSocketFactory.getSocketFactory();
    X509TrustManager trustManager = ClientSSLSocketFactory.get509TrustManager();
    OkHttpClient.Builder builder = new OkHttpClient.Builder()
            .sslSocketFactory(sslSocketFactory, trustManager);
    HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
    loggingInterceptor.setLevel(logLevel);
    builder.addInterceptor(loggingInterceptor);
    for (Interceptor interceptor : interceptors) {
        builder.addInterceptor(interceptor);
    }
    builder.followRedirects(followRedirects);
    builder.followSslRedirects(followProtocolRedirects);
    return builder.build();
}
 
Example 12
Project: li-android-sdk-core   File: LiRestv2ClientTest.java   View source code 5 votes vote down vote up
@Test
public void testValidateResponse() throws Exception {
    context = Mockito.mock(Activity.class);
    PowerMockito.mockStatic(LiClientManager.class);
    LiClientManager liClientManager = PowerMockito.mock(LiClientManager.class);

    PowerMockito.mockStatic(SSLContext.class);
    SSLContext sslContext = PowerMockito.mock(SSLContext.class);
    when(sslContext.getInstance("SSL")).thenReturn(sslContext);
    Mockito.doNothing().when(sslContext).init(isA(KeyManager[].class), isA(TrustManager[].class), isA(SecureRandom.class));
    SSLSocketFactory socketFactory = mock(SSLSocketFactory.class);
    when(sslContext.getSocketFactory()).thenReturn(socketFactory);

    PowerMockito.mockStatic(Platform.class);
    Platform platform = PowerMockito.mock(Platform.class);
    X509TrustManager trustManager = mock(X509TrustManager.class);
    when(platform.trustManager(socketFactory)).thenReturn(trustManager);
    BDDMockito.given(Platform.get()).willReturn(platform);

    BDDMockito.given(SSLContext.getInstance("SSL")).willReturn(sslContext);

    LiRestv2Client liRestv2Client = LiRestv2Client.getInstance();
    final LiBaseResponse liBaseResponse = mock(LiBaseResponse.class);
    when(liBaseResponse.getHttpCode()).thenReturn(200);
    LiRestv2Client liRestv2ClientSpy = spy(LiRestv2Client.class);
    doReturn(liBaseResponse).when(liRestv2ClientSpy).processSync(isA(LiBaseRestRequest.class));

    LiRestV2Request liBaseRestRequest = new LiRestV2Request(context, liql, "message");
    liBaseRestRequest.addQueryParam("test");

    LiBaseResponse liBaseResponse1 = liRestv2ClientSpy.processSync(liBaseRestRequest);

    Assert.assertEquals(200, liBaseResponse1.getHttpCode());
    PowerMockito.verifyStatic();
}
 
Example 13
Project: Book-Shelf   File: CustomTrust.java   View source code 5 votes vote down vote up
/**
 * Returns a trust manager that trusts {@code certificates} and none other. HTTPS services whose
 * certificates have not been signed by these certificates will fail with a {@code
 * SSLHandshakeException}.
 *
 * <p>This can be used to replace the host platform's built-in trusted certificates with a custom
 * set. This is useful in development where certificate authority-trusted certificates aren't
 * available. Or in production, to avoid reliance on third-party certificate authorities.
 *
 * <p>See also {@link CertificatePinner}, which can limit trusted certificates while still using
 * the host platform's built-in trust store.
 *
 * <h3>Warning: Customizing Trusted Certificates is Dangerous!</h3>
 *
 * <p>Relying on your own trusted certificates limits your server team's ability to update their
 * TLS certificates. By installing a specific set of trusted certificates, you take on additional
 * operational complexity and limit your ability to migrate between certificate authorities. Do
 * not use custom trusted certificates in production without the blessing of your server's TLS
 * administrator.
 */
private X509TrustManager trustManagerForCertificates(InputStream in)
        throws GeneralSecurityException {
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(in);
    if (certificates.isEmpty()) {
        throw new IllegalArgumentException("expected non-empty set of trusted certificates");
    }

    // Put the certificates a key store.
    char[] password = "password".toCharArray(); // Any password will work.
    KeyStore keyStore = newEmptyKeyStore(password);
    int index = 0;
    for (Certificate certificate : certificates) {
        String certificateAlias = Integer.toString(index++);
        keyStore.setCertificateEntry(certificateAlias, certificate);
    }

    // Use it to build an X509 trust manager.
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(
            KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, password);
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(
            TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(keyStore);
    TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
    if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
        throw new IllegalStateException("Unexpected default trust managers:"
                + Arrays.toString(trustManagers));
    }
    return (X509TrustManager) trustManagers[0];
}
 
Example 14
Project: q-mail   File: TrustManagerFactoryTest.java   View source code 5 votes vote down vote up
@Test
public void testLocallyTrustedCertificateChainNotMatchingHost() throws Exception {
    mKeyStore.addCertificate(NOT_MATCHING_HOST, PORT1, mCert3);

    X509TrustManager trustManager = TrustManagerFactory.get(NOT_MATCHING_HOST, PORT1);
    trustManager.checkServerTrusted(new X509Certificate[] { mCert3, mCaCert }, "authType");
}
 
Example 15
Project: lorne_core   File: EasyX509TrustManager.java   View source code 5 votes vote down vote up
/**
 * Constructor for EasyX509TrustManager.
 */
public EasyX509TrustManager(KeyStore keystore)
		throws NoSuchAlgorithmException, KeyStoreException {
	super();
	TrustManagerFactory factory = TrustManagerFactory
			.getInstance(TrustManagerFactory.getDefaultAlgorithm());
	factory.init(keystore);
	TrustManager[] trustmanagers = factory.getTrustManagers();
	if (trustmanagers.length == 0) {
		throw new NoSuchAlgorithmException("no trust manager found");
	}
	this.standardTrustManager = (X509TrustManager) trustmanagers[0];
}
 
Example 16
Project: RxEasyHttp   File: HttpsUtils.java   View source code 5 votes vote down vote up
private static X509TrustManager chooseTrustManager(TrustManager[] trustManagers) {
    for (TrustManager trustManager : trustManagers) {
        if (trustManager instanceof X509TrustManager) {
            return (X509TrustManager) trustManager;
        }
    }
    return null;
}
 
Example 17
Project: q-mail   File: TrustManagerFactoryTest.java   View source code 5 votes vote down vote up
private void assertCertificateRejection(X509TrustManager trustManager,
        X509Certificate[] certificates) {
    boolean certificateValid;
    try {
        trustManager.checkServerTrusted(certificates, "authType");
        certificateValid = true;
    } catch (CertificateException e) {
        certificateValid = false;
    }
    assertFalse("The certificate should have been rejected but wasn't", certificateValid);
}
 
Example 18
Project: GitHub   File: HttpsUtils.java   View source code 5 votes vote down vote up
private static X509TrustManager chooseTrustManager(TrustManager[] trustManagers)
{
    for (TrustManager trustManager : trustManagers)
    {
        if (trustManager instanceof X509TrustManager)
        {
            return (X509TrustManager) trustManager;
        }
    }
    return null;
}
 
Example 19
Project: TPlayer   File: HttpsUtils.java   View source code 5 votes vote down vote up
private static X509TrustManager chooseTrustManager(TrustManager[] trustManagers) {
    for (TrustManager trustManager : trustManagers) {
        if (trustManager instanceof X509TrustManager) {
            return (X509TrustManager) trustManager;
        }
    }
    return null;
}
 
Example 20
Project: Tusky   File: OkHttpUtils.java   View source code 5 votes vote down vote up
/**
 * Android version Nougat has a regression where elliptic curve cipher suites are supported, but
 * only the curve secp256r1 is allowed. So, first it's best to just disable all elliptic
 * ciphers, try the connection, and fall back to the all cipher suites enabled list after.
 */
private static void addNougatFixConnectionSpec(List<ConnectionSpec> specList) {
    if (Build.VERSION.SDK_INT != Build.VERSION_CODES.N) {
        return;
    }
    SSLSocketFactory socketFactory;
    try {
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(
                TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init((KeyStore) null);
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
        if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
            throw new IllegalStateException("Unexpected default trust managers:"
                    + Arrays.toString(trustManagers));
        }

        X509TrustManager trustManager = (X509TrustManager) trustManagers[0];

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, new TrustManager[] { trustManager }, null);
        socketFactory = sslContext.getSocketFactory();
    } catch (NoSuchAlgorithmException|KeyStoreException|KeyManagementException e) {
        Log.e(TAG, "Failed obtaining the SSL socket factory.");
        return;
    }
    String[] cipherSuites = socketFactory.getDefaultCipherSuites();
    ArrayList<String> allowedList = new ArrayList<>();
    for (String suite : cipherSuites) {
        if (!suite.contains("ECDH")) {
            allowedList.add(suite);
        }
    }
    ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
            .cipherSuites(allowedList.toArray(new String[0]))
            .supportsTlsExtensions(true)
            .build();
    specList.add(spec);
}
 
Example 21
Project: EasyAppleSyncAdapter   File: SSLSocketFactoryCompat.java   View source code 5 votes vote down vote up
public SSLSocketFactoryCompat(@NonNull X509TrustManager trustManager) {
    try {
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, new X509TrustManager[] {trustManager}, null);
        delegate = sslContext.getSocketFactory();
    } catch (GeneralSecurityException e) {
        throw new AssertionError(); // The system has no TLS. Just give up.
    }
}
 
Example 22
Project: GitHub   File: Jdk9Platform.java   View source code 5 votes vote down vote up
@Override public X509TrustManager trustManager(SSLSocketFactory sslSocketFactory) {
  // Not supported due to access checks on JDK 9+:
  // java.lang.reflect.InaccessibleObjectException: Unable to make member of class
  // sun.security.ssl.SSLSocketFactoryImpl accessible:  module java.base does not export
  // sun.security.ssl to unnamed module @xxx
  throw new UnsupportedOperationException(
      "clientBuilder.sslSocketFactory(SSLSocketFactory) not supported on JDK 9+");
}
 
Example 23
Project: openjdk-jdk10   File: TrustManagerTest.java   View source code 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    if (initSecmod() == false) {
        return;
    }

    if ("sparc".equals(System.getProperty("os.arch")) == false) {
        // we have not updated other platforms with the proper NSS libraries yet
        System.out.println("Test currently works only on solaris-sparc, skipping");
        return;
    }

    String configName = BASE + SEP + "fips.cfg";
    Provider p = getSunPKCS11(configName);

    System.out.println(p);
    Security.addProvider(p);

    Security.removeProvider("SunJSSE");
    Provider jsse = new com.sun.net.ssl.internal.ssl.Provider(p);
    Security.addProvider(jsse);
    System.out.println(jsse.getInfo());

    KeyStore ks = KeyStore.getInstance("PKCS11", p);
    ks.load(null, "test12".toCharArray());

    X509Certificate server = loadCertificate("certs/server.cer");
    X509Certificate ca = loadCertificate("certs/ca.cer");
    X509Certificate anchor = loadCertificate("certs/anchor.cer");

    if (args.length > 1 && "sm".equals(args[0])) {
        Policy.setPolicy(Policy.getInstance("JavaPolicy",
                new URIParameter(new File(BASE, args[1]).toURI())));
        System.setSecurityManager(new SecurityManager());
    }

    KeyStore trustStore = KeyStore.getInstance("JKS");
    trustStore.load(null, null);
    trustStore.setCertificateEntry("anchor", anchor);

    TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
    tmf.init(trustStore);

    X509TrustManager tm = (X509TrustManager)tmf.getTrustManagers()[0];

    X509Certificate[] chain = {server, ca, anchor};

    tm.checkServerTrusted(chain, "RSA");

    System.out.println("OK");
}
 
Example 24
Project: JKApp   File: HttpsCerManager.java   View source code 5 votes vote down vote up
private X509TrustManager chooseTrustManager(TrustManager[] trustManagers) {
    for (TrustManager trustManager : trustManagers) {
        if (trustManager instanceof X509TrustManager) {
            return (X509TrustManager) trustManager;
        }
    }
    return null;
}
 
Example 25
Project: okhttpUtil   File: HttpsUtil.java   View source code 5 votes vote down vote up
private static X509TrustManager chooseTrustManager(TrustManager[] trustManagers)
{
    for (TrustManager trustManager : trustManagers)
    {
        if (trustManager instanceof X509TrustManager)
        {
            return (X509TrustManager) trustManager;
        }
    }
    return null;
}
 
Example 26
Project: GitHub   File: CertificateChainCleanerTest.java   View source code 5 votes vote down vote up
@Test public void equalsFromTrustManager() throws Exception {
  SslClient client = new SslClient.Builder().build();
  X509TrustManager x509TrustManager = client.trustManager;
  assertEquals(
      CertificateChainCleaner.get(x509TrustManager),
      CertificateChainCleaner.get(x509TrustManager));
}
 
Example 27
Project: GitHub   File: CustomCipherSuites.java   View source code 5 votes vote down vote up
public CustomCipherSuites() throws GeneralSecurityException {
  // Configure cipher suites to demonstrate how to customize which cipher suites will be used for
  // an OkHttp request. In order to be selected a cipher suite must be included in both OkHttp's
  // connection spec and in the SSLSocket's enabled cipher suites array. Most applications should
  // not customize the cipher suites list.
  List<CipherSuite> customCipherSuites = Arrays.asList(
      CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
      CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
      CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
      CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384);
  final ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
      .cipherSuites(customCipherSuites.toArray(new CipherSuite[0]))
      .build();

  X509TrustManager trustManager = defaultTrustManager();
  SSLSocketFactory sslSocketFactory = defaultSslSocketFactory(trustManager);
  SSLSocketFactory customSslSocketFactory = new DelegatingSSLSocketFactory(sslSocketFactory) {
    @Override protected SSLSocket configureSocket(SSLSocket socket) throws IOException {
      socket.setEnabledCipherSuites(javaNames(spec.cipherSuites()));
      return socket;
    }
  };

  client = new OkHttpClient.Builder()
      .connectionSpecs(Collections.singletonList(spec))
      .sslSocketFactory(customSslSocketFactory, trustManager)
      .build();
}
 
Example 28
Project: hadoop   File: ReloadingX509TrustManager.java   View source code 5 votes vote down vote up
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
  throws CertificateException {
  X509TrustManager tm = trustManagerRef.get();
  if (tm != null) {
    tm.checkClientTrusted(chain, authType);
  } else {
    throw new CertificateException("Unknown client chain certificate: " +
                                   chain[0].toString());
  }
}
 
Example 29
Project: GitHub   File: CustomCipherSuites.java   View source code 5 votes vote down vote up
/** Returns a trust manager that trusts the VM's default certificate authorities. */
private X509TrustManager defaultTrustManager() throws GeneralSecurityException {
  TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(
      TrustManagerFactory.getDefaultAlgorithm());
  trustManagerFactory.init((KeyStore) null);
  TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
  if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
    throw new IllegalStateException("Unexpected default trust managers:"
        + Arrays.toString(trustManagers));
  }
  return (X509TrustManager) trustManagers[0];
}
 
Example 30
Project: GitHub   File: CustomTrust.java   View source code 5 votes vote down vote up
/**
 * Returns a trust manager that trusts {@code certificates} and none other. HTTPS services whose
 * certificates have not been signed by these certificates will fail with a {@code
 * SSLHandshakeException}.
 *
 * <p>This can be used to replace the host platform's built-in trusted certificates with a custom
 * set. This is useful in development where certificate authority-trusted certificates aren't
 * available. Or in production, to avoid reliance on third-party certificate authorities.
 *
 * <p>See also {@link CertificatePinner}, which can limit trusted certificates while still using
 * the host platform's built-in trust store.
 *
 * <h3>Warning: Customizing Trusted Certificates is Dangerous!</h3>
 *
 * <p>Relying on your own trusted certificates limits your server team's ability to update their
 * TLS certificates. By installing a specific set of trusted certificates, you take on additional
 * operational complexity and limit your ability to migrate between certificate authorities. Do
 * not use custom trusted certificates in production without the blessing of your server's TLS
 * administrator.
 */
private X509TrustManager trustManagerForCertificates(InputStream in)
    throws GeneralSecurityException {
  CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
  Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(in);
  if (certificates.isEmpty()) {
    throw new IllegalArgumentException("expected non-empty set of trusted certificates");
  }

  // Put the certificates a key store.
  char[] password = "password".toCharArray(); // Any password will work.
  KeyStore keyStore = newEmptyKeyStore(password);
  int index = 0;
  for (Certificate certificate : certificates) {
    String certificateAlias = Integer.toString(index++);
    keyStore.setCertificateEntry(certificateAlias, certificate);
  }

  // Use it to build an X509 trust manager.
  KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(
      KeyManagerFactory.getDefaultAlgorithm());
  keyManagerFactory.init(keyStore, password);
  TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(
      TrustManagerFactory.getDefaultAlgorithm());
  trustManagerFactory.init(keyStore);
  TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
  if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
    throw new IllegalStateException("Unexpected default trust managers:"
        + Arrays.toString(trustManagers));
  }
  return (X509TrustManager) trustManagers[0];
}
 
Example 31
Project: GitHub   File: OkHttpClient.java   View source code 5 votes vote down vote up
private SSLSocketFactory systemDefaultSslSocketFactory(X509TrustManager trustManager) {
  try {
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, new TrustManager[] { trustManager }, null);
    return sslContext.getSocketFactory();
  } catch (GeneralSecurityException e) {
    throw assertionError("No System TLS", e); // The system has no TLS. Just give up.
  }
}
 
Example 32
Project: GitHub   File: AndroidPlatform.java   View source code 5 votes vote down vote up
public CertificateChainCleaner buildCertificateChainCleaner(X509TrustManager trustManager) {
  try {
    Class<?> extensionsClass = Class.forName("android.net.http.X509TrustManagerExtensions");
    Constructor<?> constructor = extensionsClass.getConstructor(X509TrustManager.class);
    Object extensions = constructor.newInstance(trustManager);
    Method checkServerTrusted = extensionsClass.getMethod(
        "checkServerTrusted", X509Certificate[].class, String.class, String.class);
    return new AndroidCertificateChainCleaner(extensions, checkServerTrusted);
  } catch (Exception e) {
    return super.buildCertificateChainCleaner(trustManager);
  }
}
 
Example 33
Project: GitHub   File: Platform.java   View source code 5 votes vote down vote up
protected X509TrustManager trustManager(SSLSocketFactory sslSocketFactory) {
  // Attempt to get the trust manager from an OpenJDK socket factory. We attempt this on all
  // platforms in order to support Robolectric, which mixes classes from both Android and the
  // Oracle JDK. Note that we don't support HTTP/2 or other nice features on Robolectric.
  try {
    Class<?> sslContextClass = Class.forName("sun.security.ssl.SSLContextImpl");
    Object context = readFieldOrNull(sslSocketFactory, sslContextClass, "context");
    if (context == null) return null;
    return readFieldOrNull(context, X509TrustManager.class, "trustManager");
  } catch (ClassNotFoundException e) {
    return null;
  }
}
 
Example 34
Project: jdk8u-jdk   File: CipherTestUtils.java   View source code 5 votes vote down vote up
public AlwaysTrustManager(KeyStore keyStore)
        throws NoSuchAlgorithmException, KeyStoreException {

    TrustManagerFactory tmf
            = TrustManagerFactory.getInstance(TrustManagerFactory.
                    getDefaultAlgorithm());
    tmf.init(keyStore);

    TrustManager tms[] = tmf.getTrustManagers();
    for (TrustManager tm : tms) {
        trustManager = (X509TrustManager) tm;
        return;
    }

}
 
Example 35
Project: zabbkit-android   File: MyX509TrustManager.java   View source code 5 votes vote down vote up
private static X509TrustManager findX509TrustManager(TrustManagerFactory tmf) {
	TrustManager tms[] = tmf.getTrustManagers();
	for (final TrustManager tm : tms) {
		if (tm instanceof X509TrustManager) {
			return (X509TrustManager) tm;
		}
	}

	return null;
}
 
Example 36
Project: MVVM-JueJin   File: HttpsUtil.java   View source code 5 votes vote down vote up
private static X509TrustManager chooseTrustManager(TrustManager[] trustManagers)
{
    for (TrustManager trustManager : trustManagers)
    {
        if (trustManager instanceof X509TrustManager)
        {
            return (X509TrustManager) trustManager;
        }
    }
    return null;
}
 
Example 37
Project: GitHub   File: CustomCipherSuites.java   View source code 5 votes vote down vote up
public CustomCipherSuites() throws GeneralSecurityException {
  // Configure cipher suites to demonstrate how to customize which cipher suites will be used for
  // an OkHttp request. In order to be selected a cipher suite must be included in both OkHttp's
  // connection spec and in the SSLSocket's enabled cipher suites array. Most applications should
  // not customize the cipher suites list.
  List<CipherSuite> customCipherSuites = Arrays.asList(
      CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
      CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
      CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
      CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384);
  final ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
      .cipherSuites(customCipherSuites.toArray(new CipherSuite[0]))
      .build();

  X509TrustManager trustManager = defaultTrustManager();
  SSLSocketFactory sslSocketFactory = defaultSslSocketFactory(trustManager);
  SSLSocketFactory customSslSocketFactory = new DelegatingSSLSocketFactory(sslSocketFactory) {
    @Override protected SSLSocket configureSocket(SSLSocket socket) throws IOException {
      socket.setEnabledCipherSuites(javaNames(spec.cipherSuites()));
      return socket;
    }
  };

  client = new OkHttpClient.Builder()
      .connectionSpecs(Collections.singletonList(spec))
      .sslSocketFactory(customSslSocketFactory, trustManager)
      .build();
}
 
Example 38
Project: GitHub   File: CustomCipherSuites.java   View source code 5 votes vote down vote up
/**
 * Returns the VM's default SSL socket factory, using {@code trustManager} for trusted root
 * certificates.
 */
private SSLSocketFactory defaultSslSocketFactory(X509TrustManager trustManager)
    throws NoSuchAlgorithmException, KeyManagementException {
  SSLContext sslContext = SSLContext.getInstance("TLS");
  sslContext.init(null, new TrustManager[] { trustManager }, null);

  return sslContext.getSocketFactory();
}
 
Example 39
Project: GitHub   File: CustomCipherSuites.java   View source code 5 votes vote down vote up
/** Returns a trust manager that trusts the VM's default certificate authorities. */
private X509TrustManager defaultTrustManager() throws GeneralSecurityException {
  TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(
      TrustManagerFactory.getDefaultAlgorithm());
  trustManagerFactory.init((KeyStore) null);
  TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
  if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
    throw new IllegalStateException("Unexpected default trust managers:"
        + Arrays.toString(trustManagers));
  }
  return (X509TrustManager) trustManagers[0];
}
 
Example 40
Project: GitHub   File: CustomTrust.java   View source code 5 votes vote down vote up
public CustomTrust() {
  X509TrustManager trustManager;
  SSLSocketFactory sslSocketFactory;
  try {
    trustManager = trustManagerForCertificates(trustedCertificatesInputStream());
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, new TrustManager[] { trustManager }, null);
    sslSocketFactory = sslContext.getSocketFactory();
  } catch (GeneralSecurityException e) {
    throw new RuntimeException(e);
  }

  client = new OkHttpClient.Builder()
      .sslSocketFactory(sslSocketFactory, trustManager)
      .build();
}