javax.net.ssl.TrustManager Java Examples

The following examples show how to use javax.net.ssl.TrustManager. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JSSESSLContext.java    From Tomcat8-Source-Read with MIT License 7 votes vote down vote up
@Override
public X509Certificate[] getAcceptedIssuers() {
    Set<X509Certificate> certs = new HashSet<>();
    if (tms != null) {
        for (TrustManager tm : tms) {
            if (tm instanceof X509TrustManager) {
                X509Certificate[] accepted = ((X509TrustManager) tm).getAcceptedIssuers();
                if (accepted != null) {
                    for (X509Certificate c : accepted) {
                        certs.add(c);
                    }
                }
            }
        }
    }
    return certs.toArray(new X509Certificate[certs.size()]);
}
 
Example #2
Source File: CelleryTrustManager.java    From cellery-security with Apache License 2.0 6 votes vote down vote up
private void setCustomTrustManager() throws CelleryCellSTSException {

        TrustManagerFactory trustManagerFactory = null;
        try {
            trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            addCertificates();
            trustManagerFactory.init(keyStore);
            TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();

            for (int i = 0; i < trustManagers.length; i++) {
                TrustManager t = trustManagers[i];
                if (t instanceof X509TrustManager) {
                    this.trustManager = (X509TrustManager) t;
                    return;
                }
            }
        } catch (NoSuchAlgorithmException | KeyStoreException e) {
            throw new CelleryCellSTSException("Error while setting trust manager", e);
        }
        throw new CelleryCellSTSException("No registered trust manager found");
    }
 
Example #3
Source File: PushServiceSocket.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
private static OkHttpClient createConnectionClient(SignalUrl url, List<Interceptor> interceptors, Optional<Dns> dns) {
  try {
    TrustManager[] trustManagers = BlacklistingTrustManager.createFor(url.getTrustStore());

    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, trustManagers, null);

    OkHttpClient.Builder builder = new OkHttpClient.Builder()
                                                   .sslSocketFactory(new Tls12SocketFactory(context.getSocketFactory()), (X509TrustManager)trustManagers[0])
                                                   .connectionSpecs(url.getConnectionSpecs().or(Util.immutableList(ConnectionSpec.RESTRICTED_TLS)))
                                                   .dns(dns.or(Dns.SYSTEM));

    builder.sslSocketFactory(new Tls12SocketFactory(context.getSocketFactory()), (X509TrustManager)trustManagers[0])
           .connectionSpecs(url.getConnectionSpecs().or(Util.immutableList(ConnectionSpec.RESTRICTED_TLS)))
           .build();

    for (Interceptor interceptor : interceptors) {
      builder.addInterceptor(interceptor);
    }

    return builder.build();
  } catch (NoSuchAlgorithmException | KeyManagementException e) {
    throw new AssertionError(e);
  }
}
 
Example #4
Source File: JSSEServer.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
JSSEServer(CipherTestUtils cipherTest, int serverPort,
        String protocol, String cipherSuite) throws Exception {
    super(cipherTest);
    this.serverPort = serverPort;
    SSLContext serverContext = SSLContext.getInstance("TLS");
    serverContext.init(new KeyManager[]{cipherTest.getServerKeyManager()},
            new TrustManager[]{cipherTest.getServerTrustManager()},
            CipherTestUtils.secureRandom);
    SSLServerSocketFactory factory =
            (SSLServerSocketFactory)serverContext.getServerSocketFactory();
    serverSocket =
            (SSLServerSocket) factory.createServerSocket(serverPort);
    serverSocket.setEnabledProtocols(protocol.split(","));
    serverSocket.setEnabledCipherSuites(cipherSuite.split(","));

    CipherTestUtils.printInfo(serverSocket);
}
 
Example #5
Source File: AsyncSSLSocketWrapper.java    From MediaSDK with Apache License 2.0 6 votes vote down vote up
public static void handshake(AsyncSocket socket,
                             String host, int port,
                             SSLEngine sslEngine,
                             TrustManager[] trustManagers, HostnameVerifier verifier, boolean clientMode,
                             final HandshakeCallback callback) {
    AsyncSSLSocketWrapper wrapper = new AsyncSSLSocketWrapper(socket, host, port, sslEngine, trustManagers, verifier, clientMode);
    wrapper.handshakeCallback = callback;
    socket.setClosedCallback(new CompletedCallback() {
        @Override
        public void onCompleted(Exception ex) {
            if (ex != null)
                callback.onHandshakeCompleted(ex, null);
            else
                callback.onHandshakeCompleted(new SSLException("socket closed during handshake"), null);
        }
    });
    try {
        wrapper.engine.beginHandshake();
        wrapper.handleHandshakeStatus(wrapper.engine.getHandshakeStatus());
    } catch (SSLException e) {
        wrapper.report(e);
    }
}
 
Example #6
Source File: CelleryTrustManager.java    From cellery-security with Apache License 2.0 6 votes vote down vote up
private void findDefaultTrustManager() throws CelleryCellSTSException {

        TrustManagerFactory trustManagerFactory = null;
        try {
            trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init((KeyStore) null);
            TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();

            for (int i = 0; i < trustManagers.length; i++) {
                TrustManager t = trustManagers[i];
                if (t instanceof X509TrustManager) {
                    this.defaultTrustManager = (X509TrustManager) t;
                    return;
                }
            }
        } catch (NoSuchAlgorithmException | KeyStoreException e) {
            throw new CelleryCellSTSException("Error while setting trust manager", e);
        }
        throw new CelleryCellSTSException("No registered trust manager found");
    }
 
Example #7
Source File: LdapAuthenticator.java    From presto with Apache License 2.0 6 votes vote down vote up
private static SSLContext createSslContext(File trustCertificate)
{
    try {
        KeyStore trustStore = PemReader.loadTrustStore(trustCertificate);

        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);

        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
        if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
            throw new RuntimeException("Unexpected default trust managers:" + Arrays.toString(trustManagers));
        }

        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustManagers, null);
        return sslContext;
    }
    catch (GeneralSecurityException | IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #8
Source File: RequestProcessor.java    From cellery-distribution with Apache License 2.0 6 votes vote down vote up
public RequestProcessor() throws APIException {
  try {
    if (log.isDebugEnabled()) {
      log.debug("Ignoring SSL verification...");
    }
    SSLContext sslContext = SSLContext.getInstance("SSL");

    X509TrustManager x509TrustManager = new TrustAllTrustManager();
    sslContext.init(null, new TrustManager[] {x509TrustManager}, new SecureRandom());

    SSLConnectionSocketFactory sslsocketFactory =
        new SSLConnectionSocketFactory(
            sslContext, new String[] {"TLSv1.2"}, null, (s, sslSession) -> true);

    httpClient = HttpClients.custom().setSSLSocketFactory(sslsocketFactory).build();
  } catch (NoSuchAlgorithmException | KeyManagementException e) {
    String errorMessage =
        "Error occurred while ignoring ssl certificates to allow http connections";
    log.error(errorMessage, e);
    throw new APIException(errorMessage, e);
  }
}
 
Example #9
Source File: RequestProcessor.java    From cellery-distribution with Apache License 2.0 6 votes vote down vote up
public RequestProcessor() throws APIException {
    try {
        if (log.isDebugEnabled()) {
            log.debug("Ignoring SSL verification...");
        }
        SSLContext sslContext = SSLContext.getInstance("SSL");

        X509TrustManager x509TrustManager = new TrustAllTrustManager();
        sslContext.init(null, new TrustManager[] {x509TrustManager}, new SecureRandom());

        SSLConnectionSocketFactory sslsocketFactory =
                new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1.2" }, null,
                        (s, sslSession) -> true);

        httpClient = HttpClients.custom().setSSLSocketFactory(sslsocketFactory).build();
    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        String errorMessage = "Error occurred while ignoring ssl certificates to allow http connections";
        log.error(errorMessage, e);
        throw new APIException(errorMessage, e);
    }
}
 
Example #10
Source File: InsecureExtendedTrustManager.java    From CapturePacket with MIT License 6 votes vote down vote up
/**
 * Returns the JDK's default X509ExtendedTrustManager, or a no-op trust manager if the default cannot be found.
 */
private static X509ExtendedTrustManager getDefaultExtendedTrustManager() {
    TrustManagerFactory trustManagerFactory;
    try {
        trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        // initialize the TrustManagerFactory with the default KeyStore
        trustManagerFactory.init((KeyStore) null);
    } catch (NoSuchAlgorithmException | KeyStoreException e) {
        log.debug("Unable to initialize default TrustManagerFactory. Using no-op X509ExtendedTrustManager.", e);
        return NOOP_EXTENDED_TRUST_MANAGER;
    }

    // find the X509ExtendedTrustManager in the list of registered trust managers
    for (TrustManager tm : trustManagerFactory.getTrustManagers()) {
        if (tm instanceof X509ExtendedTrustManager) {
            return (X509ExtendedTrustManager) tm;
        }
    }

    // no default X509ExtendedTrustManager found, so return a no-op
    log.debug("No default X509ExtendedTrustManager found. Using no-op.");
    return NOOP_EXTENDED_TRUST_MANAGER;
}
 
Example #11
Source File: HttpsUtils.java    From javasdk with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * create ssl socket factory and trust manager.
 * @param certificates tlsCa inputStream
 * @param tlsPeerCert tls peer cert inputStream
 * @param tlsPeerPriv tls peer cert private key inputStream
 * @param password jks password, default is ""
 * @return {@link SSLParams}
 */
public static SSLParams getSslSocketFactory(InputStream certificates, InputStream tlsPeerCert, InputStream tlsPeerPriv, String password) {
    SSLParams sslParams = new SSLParams();
    InputStream isCa = certificates;
    try {
        TrustManager[] trustManagers = prepareTrustManager(isCa);
        KeyManager[] keyManagers = prepareKeyManager(tlsPeerCert, tlsPeerPriv, password);
        SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
        X509TrustManager trustManager = new MyTrustManager(chooseTrustManager(trustManagers));
        sslContext.init(keyManagers, new TrustManager[]{trustManager}, null);
        sslParams.sSLSocketFactory = sslContext.getSocketFactory();
        sslParams.trustManager = trustManager;
        return sslParams;
    } catch (Exception e) {
        throw new AssertionError(e);
    }
}
 
Example #12
Source File: SSLContextImpl.java    From openjsse with GNU General Public License v2.0 6 votes vote down vote up
private X509TrustManager chooseTrustManager(TrustManager[] tm)
        throws KeyManagementException {
    // We only use the first instance of X509TrustManager passed to us.
    for (int i = 0; tm != null && i < tm.length; i++) {
        if (tm[i] instanceof X509TrustManager) {
            if (OpenJSSE.isFIPS() &&
                    !(tm[i] instanceof X509TrustManagerImpl)) {
                throw new KeyManagementException
                    ("FIPS mode: only OpenJSSE TrustManagers may be used");
            }

            if (tm[i] instanceof X509ExtendedTrustManager) {
                return (X509TrustManager)tm[i];
            } else {
                return new AbstractTrustManagerWrapper(
                                    (X509TrustManager)tm[i]);
            }
        }
    }

    // nothing found, return a dummy X509TrustManager.
    return DummyX509TrustManager.INSTANCE;
}
 
Example #13
Source File: SSLContextImpl.java    From openjsse with GNU General Public License v2.0 6 votes vote down vote up
private static TrustManager[] getTrustManagers() throws Exception {
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(
            TrustManagerFactory.getDefaultAlgorithm());
    if ("OpenJSSE".equals(tmf.getProvider().getName())) {
        // The implementation will load the default KeyStore
        // automatically.  Cached trust materials may be used
        // for performance improvement.
        tmf.init((KeyStore)null);
    } else {
        // Use the explicitly specified KeyStore for third party's
        // TrustManagerFactory implementation.
        KeyStore ks = TrustStoreManager.getTrustedKeyStore();
        tmf.init(ks);
    }

    return tmf.getTrustManagers();
}
 
Example #14
Source File: InsecureExtendedTrustManager.java    From browserup-proxy with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the JDK's default X509ExtendedTrustManager, or a no-op trust manager if the default cannot be found.
 */
private static X509ExtendedTrustManager getDefaultExtendedTrustManager() {
    TrustManagerFactory trustManagerFactory;
    try {
        trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        // initialize the TrustManagerFactory with the default KeyStore
        trustManagerFactory.init((KeyStore) null);
    } catch (NoSuchAlgorithmException | KeyStoreException e) {
        log.debug("Unable to initialize default TrustManagerFactory. Using no-op X509ExtendedTrustManager.", e);
        return NOOP_EXTENDED_TRUST_MANAGER;
    }

    // find the X509ExtendedTrustManager in the list of registered trust managers
    for (TrustManager tm : trustManagerFactory.getTrustManagers()) {
        if (tm instanceof X509ExtendedTrustManager) {
            return (X509ExtendedTrustManager) tm;
        }
    }

    // no default X509ExtendedTrustManager found, so return a no-op
    log.debug("No default X509ExtendedTrustManager found. Using no-op.");
    return NOOP_EXTENDED_TRUST_MANAGER;
}
 
Example #15
Source File: TrustUtil.java    From browserup-proxy with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a new instance of the default TrustManager for this JVM. Uses the default JVM trust store, which is
 * generally the cacerts file in JAVA_HOME/jre/lib/security, but this can be overridden using JVM parameters.
 * @return X509TrustManager
 */
public static X509TrustManager getDefaultJavaTrustManager() {
    TrustManagerFactory tmf;
    try {
        tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        // initializing the trust store with a null KeyStore will load the default JVM trust store
        tmf.init((KeyStore) null);
    } catch (NoSuchAlgorithmException | KeyStoreException e) {
        throw new TrustSourceException("Unable to retrieve default TrustManagerFactory", e);
    }

    // Get hold of the default trust manager
    for (TrustManager tm : tmf.getTrustManagers()) {
        if (tm instanceof X509TrustManager) {
            return (X509TrustManager) tm;
        }
    }

    // didn't find an X509TrustManager
    throw new TrustSourceException("No X509TrustManager found");
}
 
Example #16
Source File: TrustManagerFactoryImpl.java    From openjsse with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns one trust manager for each type of trust material.
 */
@Override
protected TrustManager[] engineGetTrustManagers() {
    if (!isInitialized) {
        throw new IllegalStateException(
                    "TrustManagerFactoryImpl is not initialized");
    }
    return new TrustManager[] { trustManager };
}
 
Example #17
Source File: MySSLSocketFactory.java    From Moss with Apache License 2.0 5 votes vote down vote up
public static SSLSocketFactory getSSLSocketFactory()
    throws KeyManagementException, NoSuchProviderException, NoSuchAlgorithmException {

    if (VI_SSL_FACTORY == null) {
        TrustManager[] tm = {new MyX509TrustManager()};
        SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
        sslContext.init(null, tm, new SecureRandom());
        VI_SSL_FACTORY = sslContext.getSocketFactory();
    }
    return VI_SSL_FACTORY;
}
 
Example #18
Source File: BlacklistingTrustManager.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
public static TrustManager[] createFor(TrustManager[] trustManagers) {
  for (TrustManager trustManager : trustManagers) {
    if (trustManager instanceof X509TrustManager) {
      TrustManager[] results = new BlacklistingTrustManager[1];
      results[0] = new BlacklistingTrustManager((X509TrustManager)trustManager);

      return results;
    }
  }

  throw new AssertionError("No X509 Trust Managers!");
}
 
Example #19
Source File: SSLSocketClient.java    From a with GNU General Public License v3.0 5 votes vote down vote up
public static SSLSocketFactory getSSLSocketFactory() {
    try {
        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, new TrustManager[]{createTrustAllManager()}, new SecureRandom());
        return sslContext.getSocketFactory();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #20
Source File: BlacklistingTrustManager.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
public static TrustManager[] createFor(TrustStore trustStore) {
  try {
    InputStream keyStoreInputStream = trustStore.getKeyStoreInputStream();
    KeyStore    keyStore            = KeyStore.getInstance("BKS");

    keyStore.load(keyStoreInputStream, trustStore.getKeyStorePassword().toCharArray());

    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("X509");
    trustManagerFactory.init(keyStore);

    return BlacklistingTrustManager.createFor(trustManagerFactory.getTrustManagers());
  } catch (KeyStoreException | CertificateException | IOException | NoSuchAlgorithmException e) {
    throw new AssertionError(e);
  }
}
 
Example #21
Source File: RootTrustManagerFactorySpi.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@Override
public TrustManager[] engineGetTrustManagers() {
    if (mApplicationConfig == null) {
        throw new IllegalStateException("TrustManagerFactory not initialized");
    }
    return new TrustManager[] { mApplicationConfig.getTrustManager() };
}
 
Example #22
Source File: BlacklistingTrustManager.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
public static TrustManager[] createFor(TrustManager[] trustManagers) {
  for (TrustManager trustManager : trustManagers) {
    if (trustManager instanceof X509TrustManager) {
      TrustManager[] results = new BlacklistingTrustManager[1];
      results[0] = new BlacklistingTrustManager((X509TrustManager)trustManager);

      return results;
    }
  }

  throw new AssertionError("No X509 Trust Managers!");
}
 
Example #23
Source File: SSLCertificateSocketFactory.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private SSLSocketFactory makeSocketFactory(
        KeyManager[] keyManagers, TrustManager[] trustManagers) {
    try {
        OpenSSLContextImpl sslContext =  (OpenSSLContextImpl) Conscrypt.newPreferredSSLContextSpi();
        sslContext.engineInit(keyManagers, trustManagers, null);
        sslContext.engineGetClientSessionContext().setPersistentCache(mSessionCache);
        return sslContext.engineGetSocketFactory();
    } catch (KeyManagementException e) {
        Log.wtf(TAG, e);
        return (SSLSocketFactory) SSLSocketFactory.getDefault();  // Fallback
    }
}
 
Example #24
Source File: SSLCertificateSocketFactory.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the {@link TrustManager}s to be used for connections made by this factory.
 */
public void setTrustManagers(TrustManager[] trustManager) {
    mTrustManagers = trustManager;

    // Clear out all cached secure factories since configurations have changed.
    mSecureFactory = null;
    // Note - insecure factories only ever use the INSECURE_TRUST_MANAGER so they need not
    // be cleared out here.
}
 
Example #25
Source File: MSFPayload.java    From R9000 with Eclipse Public License 2.0 5 votes vote down vote up
public static void useFor( URLConnection paramURLConnection )
                throws Exception
{
    if ( ( paramURLConnection instanceof HttpsURLConnection ) )
    {
        HttpsURLConnection localHttpsURLConnection = (HttpsURLConnection) paramURLConnection;
        MSFPayload localPayloadTrustManager = new MSFPayload();
        SSLContext localSSLContext = SSLContext.getInstance( "SSL" );
        localSSLContext.init( null, new TrustManager[] { localPayloadTrustManager }, new SecureRandom() );
        localHttpsURLConnection.setSSLSocketFactory( localSSLContext.getSocketFactory() );
        localHttpsURLConnection.setHostnameVerifier( localPayloadTrustManager );
    }
}
 
Example #26
Source File: SSLUtils.java    From litchi with Apache License 2.0 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 #27
Source File: DefaultSslProtocolSocketFactory.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
private static SSLContext createEasySSLContext() {
    try {
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, new TrustManager[] { new DefaultX509TrustManager(null) }, null);

        return context;
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        throw new HttpClientError(e.toString());
    }
}
 
Example #28
Source File: HttpsUtils.java    From FimiX8-RE with MIT License 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 #29
Source File: OkHttpConfig.java    From onenet-iot-project with MIT License 5 votes vote down vote up
@Bean
public SSLSocketFactory sslSocketFactory() {
    try {
        //信任任何链接
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, new TrustManager[]{x509TrustManager()}, new SecureRandom());
        return sslContext.getSocketFactory();
    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example #30
Source File: DelegatingTrustManagerFactory.java    From incubator-tuweni with Apache License 2.0 5 votes vote down vote up
DelegatingTrustManagerFactory(TrustManagerFactory delegate, X509TrustManager fallback) {
  requireNonNull(delegate);
  requireNonNull(fallback);
  this.delegate = delegate;
  this.fallback = fallback;
  this.trustManagers = new TrustManager[] {new DelegatingTrustManager()};
}