Search in sources :

Example 56 with TrustManagerFactory

use of javax.net.ssl.TrustManagerFactory in project okhttp by square.

the class OkHttpClient method systemDefaultTrustManager.

private X509TrustManager systemDefaultTrustManager() {
    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));
        }
        return (X509TrustManager) trustManagers[0];
    } catch (GeneralSecurityException e) {
        // The system has no TLS. Just give up.
        throw new AssertionError();
    }
}
Also used : X509TrustManager(javax.net.ssl.X509TrustManager) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) GeneralSecurityException(java.security.GeneralSecurityException) TrustManager(javax.net.ssl.TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager)

Example 57 with TrustManagerFactory

use of javax.net.ssl.TrustManagerFactory in project okhttp by square.

the class URLConnectionTest method connectViaHttpsReusingConnectionsDifferentFactories.

@Test
public void connectViaHttpsReusingConnectionsDifferentFactories() throws Exception {
    server.useHttps(sslClient.socketFactory, false);
    server.enqueue(new MockResponse().setBody("this response comes via HTTPS"));
    server.enqueue(new MockResponse().setBody("another response via HTTPS"));
    // install a custom SSL socket factory so the server can be authorized
    urlFactory.setClient(urlFactory.client().newBuilder().sslSocketFactory(sslClient.socketFactory, sslClient.trustManager).hostnameVerifier(new RecordingHostnameVerifier()).build());
    HttpURLConnection connection1 = urlFactory.open(server.url("/").url());
    assertContent("this response comes via HTTPS", connection1);
    SSLContext sslContext2 = SSLContext.getInstance("TLS");
    sslContext2.init(null, null, null);
    SSLSocketFactory sslSocketFactory2 = sslContext2.getSocketFactory();
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init((KeyStore) null);
    X509TrustManager trustManager = (X509TrustManager) trustManagerFactory.getTrustManagers()[0];
    urlFactory.setClient(urlFactory.client().newBuilder().sslSocketFactory(sslSocketFactory2, trustManager).build());
    HttpURLConnection connection2 = urlFactory.open(server.url("/").url());
    try {
        readAscii(connection2.getInputStream(), Integer.MAX_VALUE);
        fail("without an SSL socket factory, the connection should fail");
    } catch (SSLException expected) {
    }
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) HttpURLConnection(java.net.HttpURLConnection) OkHttpURLConnection(okhttp3.internal.huc.OkHttpURLConnection) X509TrustManager(javax.net.ssl.X509TrustManager) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) SSLContext(javax.net.ssl.SSLContext) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) SSLException(javax.net.ssl.SSLException) Test(org.junit.Test)

Example 58 with TrustManagerFactory

use of javax.net.ssl.TrustManagerFactory in project okhttp by square.

the class CustomTrust method trustManagerForCertificates.

/**
   * 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.
    // Any password will work.
    char[] password = "password".toCharArray();
    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];
}
Also used : CertificateFactory(java.security.cert.CertificateFactory) KeyStore(java.security.KeyStore) KeyManagerFactory(javax.net.ssl.KeyManagerFactory) TrustManager(javax.net.ssl.TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) Certificate(java.security.cert.Certificate)

Example 59 with TrustManagerFactory

use of javax.net.ssl.TrustManagerFactory in project cassandra by apache.

the class SSLFactory method createSSLContext.

@SuppressWarnings("resource")
public static SSLContext createSSLContext(EncryptionOptions options, boolean buildTruststore) throws IOException {
    FileInputStream tsf = null;
    FileInputStream ksf = null;
    SSLContext ctx;
    try {
        ctx = SSLContext.getInstance(options.protocol);
        TrustManager[] trustManagers = null;
        if (buildTruststore) {
            tsf = new FileInputStream(options.truststore);
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(options.algorithm);
            KeyStore ts = KeyStore.getInstance(options.store_type);
            ts.load(tsf, options.truststore_password.toCharArray());
            tmf.init(ts);
            trustManagers = tmf.getTrustManagers();
        }
        ksf = new FileInputStream(options.keystore);
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(options.algorithm);
        KeyStore ks = KeyStore.getInstance(options.store_type);
        ks.load(ksf, options.keystore_password.toCharArray());
        if (!checkedExpiry) {
            for (Enumeration<String> aliases = ks.aliases(); aliases.hasMoreElements(); ) {
                String alias = aliases.nextElement();
                if (ks.getCertificate(alias).getType().equals("X.509")) {
                    Date expires = ((X509Certificate) ks.getCertificate(alias)).getNotAfter();
                    if (expires.before(new Date()))
                        logger.warn("Certificate for {} expired on {}", alias, expires);
                }
            }
            checkedExpiry = true;
        }
        kmf.init(ks, options.keystore_password.toCharArray());
        ctx.init(kmf.getKeyManagers(), trustManagers, null);
    } catch (Exception e) {
        throw new IOException("Error creating the initializing the SSL Context", e);
    } finally {
        FileUtils.closeQuietly(tsf);
        FileUtils.closeQuietly(ksf);
    }
    return ctx;
}
Also used : SSLContext(javax.net.ssl.SSLContext) IOException(java.io.IOException) KeyStore(java.security.KeyStore) FileInputStream(java.io.FileInputStream) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) IOException(java.io.IOException) TrustManager(javax.net.ssl.TrustManager) KeyManagerFactory(javax.net.ssl.KeyManagerFactory) TrustManagerFactory(javax.net.ssl.TrustManagerFactory)

Example 60 with TrustManagerFactory

use of javax.net.ssl.TrustManagerFactory in project XobotOS by xamarin.

the class SSLParametersImpl method createDefaultTrustManager.

private static X509TrustManager createDefaultTrustManager() {
    try {
        String algorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);
        tmf.init((KeyStore) null);
        TrustManager[] tms = tmf.getTrustManagers();
        X509TrustManager trustManager = findX509TrustManager(tms);
        return trustManager;
    } catch (NoSuchAlgorithmException e) {
        return null;
    } catch (KeyStoreException e) {
        return null;
    }
}
Also used : X509TrustManager(javax.net.ssl.X509TrustManager) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStoreException(java.security.KeyStoreException) TrustManager(javax.net.ssl.TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager)

Aggregations

TrustManagerFactory (javax.net.ssl.TrustManagerFactory)504 KeyStore (java.security.KeyStore)318 SSLContext (javax.net.ssl.SSLContext)247 TrustManager (javax.net.ssl.TrustManager)186 KeyManagerFactory (javax.net.ssl.KeyManagerFactory)180 IOException (java.io.IOException)129 FileInputStream (java.io.FileInputStream)123 X509TrustManager (javax.net.ssl.X509TrustManager)123 InputStream (java.io.InputStream)113 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)113 KeyStoreException (java.security.KeyStoreException)98 CertificateException (java.security.cert.CertificateException)87 KeyManagementException (java.security.KeyManagementException)64 X509Certificate (java.security.cert.X509Certificate)60 SecureRandom (java.security.SecureRandom)53 KeyManager (javax.net.ssl.KeyManager)48 CertificateFactory (java.security.cert.CertificateFactory)37 GeneralSecurityException (java.security.GeneralSecurityException)36 File (java.io.File)35 Certificate (java.security.cert.Certificate)34