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

项目:q-mail    文件:TrustManagerFactoryTest.java   
@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");
}
项目:the-vigilantes    文件:ExportControlled.java   
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);
        }
    }
}
项目:Android_Code_Arbiter    文件:KeyStoresTrustManager.java   
@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;
}
项目:outland    文件:CertificateLoader.java   
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());
  }
}
项目:OpenVertretung    文件:ExportControlled.java   
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);
        }
    }
}
项目:GitHub    文件:Main.java   
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();
}
项目:dracoon-dropzone    文件:RestClient.java   
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;
    }
}
项目:springboot-shiro-cas-mybatis    文件:FileTrustStoreSslSocketFactory.java   
@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");
}
项目:Android_Code_Arbiter    文件:KeyStoresTrustManager.java   
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()]);
}
项目:ProyectoPacientes    文件:ExportControlled.java   
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);
        }
    }
}
项目:super-volley    文件:SuperVolley.java   
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();
}
项目:li-android-sdk-core    文件:LiRestv2ClientTest.java   
@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();
}
项目:Book-Shelf    文件:CustomTrust.java   
/**
 * 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];
}
项目:q-mail    文件:TrustManagerFactoryTest.java   
@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");
}
项目:lorne_core    文件:EasyX509TrustManager.java   
/**
 * 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];
}
项目:RxEasyHttp    文件:HttpsUtils.java   
private static X509TrustManager chooseTrustManager(TrustManager[] trustManagers) {
    for (TrustManager trustManager : trustManagers) {
        if (trustManager instanceof X509TrustManager) {
            return (X509TrustManager) trustManager;
        }
    }
    return null;
}
项目:q-mail    文件:TrustManagerFactoryTest.java   
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);
}
项目:GitHub    文件:HttpsUtils.java   
private static X509TrustManager chooseTrustManager(TrustManager[] trustManagers)
{
    for (TrustManager trustManager : trustManagers)
    {
        if (trustManager instanceof X509TrustManager)
        {
            return (X509TrustManager) trustManager;
        }
    }
    return null;
}
项目:TPlayer    文件:HttpsUtils.java   
private static X509TrustManager chooseTrustManager(TrustManager[] trustManagers) {
    for (TrustManager trustManager : trustManagers) {
        if (trustManager instanceof X509TrustManager) {
            return (X509TrustManager) trustManager;
        }
    }
    return null;
}
项目:Tusky    文件:OkHttpUtils.java   
/**
 * 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);
}
项目:EasyAppleSyncAdapter    文件:SSLSocketFactoryCompat.java   
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.
    }
}
项目:GitHub    文件:Jdk9Platform.java   
@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+");
}
项目:openjdk-jdk10    文件:TrustManagerTest.java   
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");
}
项目:JKApp    文件:HttpsCerManager.java   
private X509TrustManager chooseTrustManager(TrustManager[] trustManagers) {
    for (TrustManager trustManager : trustManagers) {
        if (trustManager instanceof X509TrustManager) {
            return (X509TrustManager) trustManager;
        }
    }
    return null;
}
项目:okhttpUtil    文件:HttpsUtil.java   
private static X509TrustManager chooseTrustManager(TrustManager[] trustManagers)
{
    for (TrustManager trustManager : trustManagers)
    {
        if (trustManager instanceof X509TrustManager)
        {
            return (X509TrustManager) trustManager;
        }
    }
    return null;
}
项目:GitHub    文件:CertificateChainCleanerTest.java   
@Test public void equalsFromTrustManager() throws Exception {
  SslClient client = new SslClient.Builder().build();
  X509TrustManager x509TrustManager = client.trustManager;
  assertEquals(
      CertificateChainCleaner.get(x509TrustManager),
      CertificateChainCleaner.get(x509TrustManager));
}
项目:GitHub    文件:CustomCipherSuites.java   
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();
}
项目:hadoop    文件:ReloadingX509TrustManager.java   
@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());
  }
}
项目:GitHub    文件:CustomCipherSuites.java   
/** 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];
}
项目:GitHub    文件:CustomTrust.java   
/**
 * 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];
}
项目:GitHub    文件:OkHttpClient.java   
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.
  }
}
项目:GitHub    文件:AndroidPlatform.java   
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);
  }
}
项目:GitHub    文件:Platform.java   
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;
  }
}
项目:jdk8u-jdk    文件:CipherTestUtils.java   
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;
    }

}
项目:zabbkit-android    文件:MyX509TrustManager.java   
private static X509TrustManager findX509TrustManager(TrustManagerFactory tmf) {
    TrustManager tms[] = tmf.getTrustManagers();
    for (final TrustManager tm : tms) {
        if (tm instanceof X509TrustManager) {
            return (X509TrustManager) tm;
        }
    }

    return null;
}
项目:MVVM-JueJin    文件:HttpsUtil.java   
private static X509TrustManager chooseTrustManager(TrustManager[] trustManagers)
{
    for (TrustManager trustManager : trustManagers)
    {
        if (trustManager instanceof X509TrustManager)
        {
            return (X509TrustManager) trustManager;
        }
    }
    return null;
}
项目:GitHub    文件:CustomCipherSuites.java   
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();
}
项目:GitHub    文件:CustomCipherSuites.java   
/**
 * 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();
}
项目:GitHub    文件:CustomCipherSuites.java   
/** 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];
}
项目:GitHub    文件:CustomTrust.java   
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();
}