Java Code Examples for javax.net.ssl.TrustManager

The following examples show how to use javax.net.ssl.TrustManager. These examples are extracted from open source projects. 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 Project: Tomcat8-Source-Read   Author: chenmudu   File: JSSESSLContext.java    License: 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 Project: mollyim-android   Author: mollyim   File: PushServiceSocket.java    License: 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 #3
Source Project: MediaSDK   Author: JeffMony   File: AsyncSSLSocketWrapper.java    License: 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 #4
Source Project: cellery-security   Author: wso2   File: CelleryTrustManager.java    License: 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 #5
Source Project: cellery-security   Author: wso2   File: CelleryTrustManager.java    License: 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 #6
Source Project: presto   Author: prestosql   File: LdapAuthenticator.java    License: 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 #7
Source Project: cellery-distribution   Author: wso2   File: RequestProcessor.java    License: 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 #8
Source Project: cellery-distribution   Author: wso2   File: RequestProcessor.java    License: 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 Project: CapturePacket   Author: huanglqweiwei   File: InsecureExtendedTrustManager.java    License: 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 #10
Source Project: javasdk   Author: hyperchain   File: HttpsUtils.java    License: 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 #11
Source Project: openjsse   Author: openjsse   File: SSLContextImpl.java    License: 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 #12
Source Project: openjsse   Author: openjsse   File: SSLContextImpl.java    License: 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 #13
Source Project: browserup-proxy   Author: browserup   File: InsecureExtendedTrustManager.java    License: 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 #14
Source Project: browserup-proxy   Author: browserup   File: TrustUtil.java    License: 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 #15
Source Project: dragonwell8_jdk   Author: alibaba   File: JSSEServer.java    License: 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 #16
Source Project: Tomcat8-Source-Read   Author: chenmudu   File: OpenSSLContext.java    License: MIT License 5 votes vote down vote up
private static X509TrustManager chooseTrustManager(TrustManager[] managers) {
    for (TrustManager m : managers) {
        if (m instanceof X509TrustManager) {
            return (X509TrustManager) m;
        }
    }
    throw new IllegalStateException(sm.getString("openssl.trustManagerMissing"));
}
 
Example #17
Source Project: TencentKona-8   Author: Tencent   File: CipherTestUtils.java    License: GNU General Public License v2.0 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 #18
Source Project: ans-android-sdk   Author: analysys   File: CommonUtils.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * 需要配置证书
 */
private static SSLSocketFactory getUserSSLSocketFactory(Context context, String certName) {
    try {
        //读取证书
        AssetManager am = context.getAssets();
        if (am != null) {
            // 读取证书文件
            InputStream is = am.open(certName);
            InputStream input = new BufferedInputStream(is);
            CertificateFactory cerFactory = CertificateFactory.getInstance("X.509");
            Certificate cer = cerFactory.generateCertificate(input);
            // 创建keystore,包含我们的证书
            String keySoreType = KeyStore.getDefaultType();
            KeyStore keyStore = KeyStore.getInstance(keySoreType);
            keyStore.load(null);
            keyStore.setCertificateEntry("cert", cer);
            // 创建一个 trustManager,仅把 keystore 中的证书 作为信任的锚点
            String algorithm = TrustManagerFactory.getDefaultAlgorithm();
            TrustManagerFactory trustManagerFactory =
                    TrustManagerFactory.getInstance(algorithm);
            trustManagerFactory.init(keyStore);
            TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
            // 用 TrustManager 初始化一个SSLContext
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustManagers, null);
            return sslContext.getSocketFactory();
        }
    } catch (Throwable ignore) {
        ExceptionUtil.exceptionThrow(ignore);
    }
    return null;
}
 
Example #19
Source Project: incubator-tuweni   Author: apache   File: DelegatingTrustManagerFactory.java    License: 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()};
}
 
Example #20
Source Project: codewind-eclipse   Author: eclipse   File: HttpUtil.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private static SSLContext getTrustAllCertsContext(X509TrustManager manager) {
	try {
		SSLContext context = SSLContext.getInstance("TLSv1.2");
		context.init(new KeyManager[0], new TrustManager[] { manager }, new SecureRandom());
		return context;
	} catch (Exception e) {
		Logger.logError("An error occurred creating a trust all certs context", e);
	}
	return null;
}
 
Example #21
Source Project: mollyim-android   Author: mollyim   File: WebSocketConnection.java    License: GNU General Public License v3.0 5 votes vote down vote up
private Pair<SSLSocketFactory, X509TrustManager> createTlsSocketFactory(TrustStore trustStore) {
  try {
    SSLContext     context       = SSLContext.getInstance("TLS");
    TrustManager[] trustManagers = BlacklistingTrustManager.createFor(trustStore);
    context.init(null, trustManagers, null);

    return new Pair<>(context.getSocketFactory(), (X509TrustManager)trustManagers[0]);
  } catch (NoSuchAlgorithmException | KeyManagementException e) {
    throw new AssertionError(e);
  }
}
 
Example #22
Source Project: mollyim-android   Author: mollyim   File: BlacklistingTrustManager.java    License: 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 Project: mollyim-android   Author: mollyim   File: BlacklistingTrustManager.java    License: 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 #24
Source Project: MediaSDK   Author: JeffMony   File: AsyncSSLSocketWrapper.java    License: Apache License 2.0 5 votes vote down vote up
private AsyncSSLSocketWrapper(AsyncSocket socket,
                              String host, int port,
                              SSLEngine sslEngine,
                              TrustManager[] trustManagers, HostnameVerifier verifier, boolean clientMode) {
    mSocket = socket;
    hostnameVerifier = verifier;
    this.clientMode = clientMode;
    this.trustManagers = trustManagers;
    this.engine = sslEngine;

    mHost = host;
    mPort = port;
    engine.setUseClientMode(clientMode);
    mSink = new BufferedDataSink(socket);
    mSink.setWriteableCallback(new WritableCallback() {
        @Override
        public void onWriteable() {
            if (mWriteableCallback != null)
                mWriteableCallback.onWriteable();
        }
    });

    // on pause, the emitter is paused to prevent the buffered
    // socket and itself from firing.
    // on resume, emitter is resumed, ssl buffer is flushed as well
    mSocket.setEndCallback(new CompletedCallback() {
        @Override
        public void onCompleted(Exception ex) {
            if (mEnded)
                return;
            mEnded = true;
            mEndException = ex;
            if (!pending.hasRemaining() && mEndCallback != null)
                mEndCallback.onCompleted(ex);
        }
    });

    mSocket.setDataCallback(dataCallback);
}
 
Example #25
Source Project: micro-integrator   Author: wso2   File: SSLHandlerFactory.java    License: Apache License 2.0 5 votes vote down vote up
public SSLHandlerFactory(InboundWebsocketSSLConfiguration sslConfiguration) {
    String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
    if (algorithm == null) {
        algorithm = "SunX509";
    }
    try {
        KeyStore keyStore = getKeyStore(sslConfiguration.getKeyStore(), sslConfiguration.getKeyStorePass());
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(algorithm);
        keyManagerFactory.init(keyStore, sslConfiguration.getCertPass() != null ?
                sslConfiguration.getCertPass().toCharArray() :
                sslConfiguration.getKeyStorePass().toCharArray());
        KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();
        TrustManager[] trustManagers = null;
        if (sslConfiguration.getTrustStore() != null) {
            this.needClientAuth = true;
            KeyStore trustStore = getKeyStore(sslConfiguration.getTrustStore(),
                                              sslConfiguration.getTrustStorePass());
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(algorithm);
            trustManagerFactory.init(trustStore);
            trustManagers = trustManagerFactory.getTrustManagers();
        }
        serverContext = SSLContext.getInstance(protocol);
        serverContext.init(keyManagers, trustManagers, null);
        cipherSuites = sslConfiguration.getCipherSuites();
        sslProtocols = sslConfiguration.getSslProtocols();
    } catch (UnrecoverableKeyException | KeyManagementException | NoSuchAlgorithmException | KeyStoreException | IOException ex) {
        throw new IllegalArgumentException("Failed to initialize the server side SSLContext", ex);
    }
}
 
Example #26
Source Project: grpc-nebula-java   Author: grpc-nebula   File: TesterOkHttpChannelBuilder.java    License: Apache License 2.0 5 votes vote down vote up
private static TrustManager[] getTrustManagers(InputStream testCa) throws Exception {
  KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
  ks.load(null);
  CertificateFactory cf = CertificateFactory.getInstance("X.509");
  X509Certificate cert = (X509Certificate) cf.generateCertificate(testCa);
  X500Principal principal = cert.getSubjectX500Principal();
  ks.setCertificateEntry(principal.getName("RFC2253"), cert);
  // Set up trust manager factory to use our key store.
  TrustManagerFactory trustManagerFactory =
      TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
  trustManagerFactory.init(ks);
  return trustManagerFactory.getTrustManagers();
}
 
Example #27
Source Project: netty-4.1.22   Author: tianheframe   File: ReferenceCountedOpenSslContext.java    License: Apache License 2.0 5 votes vote down vote up
protected static X509TrustManager chooseTrustManager(TrustManager[] managers) {
    for (TrustManager m : managers) {
        if (m instanceof X509TrustManager) {
            return (X509TrustManager) m;
        }
    }
    throw new IllegalStateException("no X509TrustManager found");
}
 
Example #28
Source Project: PowerTunnel   Author: krlvm   File: CertificateHelper.java    License: MIT License 5 votes vote down vote up
public static TrustManager[] getTrustManagers(KeyStore keyStore)
        throws KeyStoreException, NoSuchAlgorithmException,
        NoSuchProviderException {
    String trustManAlg = TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(trustManAlg
    /* , PROVIDER_NAME */);
    tmf.init(keyStore);
    return tmf.getTrustManagers();
}
 
Example #29
Source Project: PowerTunnel   Author: krlvm   File: CertificateHelper.java    License: MIT License 5 votes vote down vote up
public static SSLContext newClientContext(KeyManager[] keyManagers,
        TrustManager[] trustManagers) throws NoSuchAlgorithmException,
        KeyManagementException, NoSuchProviderException {
    SSLContext result = newSSLContext();
    result.init(keyManagers, trustManagers, null);
    return result;
}
 
Example #30
Source Project: PowerTunnel   Author: krlvm   File: MergeTrustManager.java    License: MIT License 5 votes vote down vote up
private X509TrustManager defaultTrustManager(KeyStore trustStore)
        throws NoSuchAlgorithmException, KeyStoreException {
    String tma = TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(tma);
    tmf.init(trustStore);
    TrustManager[] trustManagers = tmf.getTrustManagers();
    for (TrustManager each : trustManagers) {
        if (each instanceof X509TrustManager) {
            return (X509TrustManager) each;
        }
    }
    throw new IllegalStateException("Missed X509TrustManager in "
            + Arrays.toString(trustManagers));
}