Java Code Examples for javax.net.ssl.TrustManagerFactory#getInstance()

The following examples show how to use javax.net.ssl.TrustManagerFactory#getInstance() . 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: AuthSSLProtocolSocketFactory.java    From iaf with Apache License 2.0 7 votes vote down vote up
private static TrustManager[] createTrustManagers(final KeyStore keystore, String algorithm)
    throws KeyStoreException, NoSuchAlgorithmException
{ 
    if (keystore == null) {
        throw new IllegalArgumentException("Keystore may not be null");
    }
    log.debug("Initializing trust manager");
    if (StringUtils.isEmpty(algorithm)) {
    	algorithm=TrustManagerFactory.getDefaultAlgorithm();
    	log.debug("using default TrustManager algorithm ["+algorithm+"]");
    } else {
    	log.debug("using configured TrustManager algorithm ["+algorithm+"]");
    }
    TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(algorithm);
    tmfactory.init(keystore);
    TrustManager[] trustmanagers = tmfactory.getTrustManagers();
    return trustmanagers; 
}
 
Example 2
Source File: ClientAuthX509TrustManager.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * This method reloads the TrustManager by reading the carbon server's default trust store file
 *
 * @throws Exception
 */
private void setupTrustManager() throws Exception {

    TrustManagerFactory trustManagerFactory =
            TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    KeyStore clientTrustStore;
    try (InputStream trustStoreInputStream =new FileInputStream(TRUST_STORE_LOCATION)){

        clientTrustStore = KeyStore.getInstance(TRUST_STORE_TYPE);
        clientTrustStore.load(trustStoreInputStream, null);

        trustManagerFactory.init(clientTrustStore);
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();

        for (TrustManager t : trustManagers) {
            if (t instanceof X509TrustManager) {
                trustManager = (X509TrustManager) t;
                System.setProperty(PROP_TRUST_STORE_UPDATE_REQUIRED, Boolean.FALSE.toString());
                return;
            }
        }
        throw new IdentityException("No X509TrustManager in TrustManagerFactory");
    }
}
 
Example 3
Source File: TestUtils.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an SSLSocketFactory which contains {@code certChainFile} as its only root certificate.
 */
public static SSLSocketFactory newSslSocketFactoryForCa(Provider provider,
                                                        File certChainFile) throws Exception {
  KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
  ks.load(null, null);
  CertificateFactory cf = CertificateFactory.getInstance("X.509");
  BufferedInputStream in = new BufferedInputStream(new FileInputStream(certChainFile));
  try {
    X509Certificate cert = (X509Certificate) cf.generateCertificate(in);
    X500Principal principal = cert.getSubjectX500Principal();
    ks.setCertificateEntry(principal.getName("RFC2253"), cert);
  } finally {
    in.close();
  }

  // Set up trust manager factory to use our key store.
  TrustManagerFactory trustManagerFactory =
      TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
  trustManagerFactory.init(ks);
  SSLContext context = SSLContext.getInstance("TLS", provider);
  context.init(null, trustManagerFactory.getTrustManagers(), null);
  return context.getSocketFactory();
}
 
Example 4
Source File: TransportSupport.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
private static TrustManagerFactory loadTrustManagerFactory(TransportOptions options) throws Exception {
    if (options.isTrustAll()) {
        return InsecureTrustManagerFactory.INSTANCE;
    }

    if (options.getTrustStoreLocation() == null) {
        return null;
    }

    TrustManagerFactory fact = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());

    String storeLocation = options.getTrustStoreLocation();
    String storePassword = options.getTrustStorePassword();
    String storeType = options.getTrustStoreType();

    LOG.trace("Attempt to load TrustStore from location {} of type {}", storeLocation, storeType);

    KeyStore trustStore = loadStore(storeLocation, storePassword, storeType);
    fact.init(trustStore);

    return fact;
}
 
Example 5
Source File: ExtendedOkHttpClientBuilder.java    From TowerCollector with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * If on [Build.VERSION_CODES.LOLLIPOP] or lower, sets [OkHttpClient.Builder.sslSocketFactory] to an instance of
 * [Tls12SocketFactory] that wraps the default [SSLContext.getSocketFactory] for [TlsVersion.TLS_1_2].
 * Does nothing when called on [Build.VERSION_CODES.LOLLIPOP_MR1] or higher.
 * <p>
 * For some reason, Android supports TLS v1.2 from [Build.VERSION_CODES.JELLY_BEAN], but the spec only has it
 * enabled by default from API [Build.VERSION_CODES.KITKAT]. Furthermore, some devices on
 * [Build.VERSION_CODES.LOLLIPOP] don't have it enabled, despite the spec saying they should.
 *
 * @return the (potentially modified) [OkHttpClient.Builder]
 */
private OkHttpClient.Builder enableTls12(OkHttpClient.Builder clientBuilder) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1) {
        try {
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init((KeyStore) null);
            X509TrustManager trustManager = (X509TrustManager) trustManagerFactory.getTrustManagers()[0];

            SSLContext sc = SSLContext.getInstance(TlsVersion.TLS_1_2.javaName());
            sc.init(null, new TrustManager[]{trustManager}, null);
            clientBuilder.sslSocketFactory(new Tls12SocketFactory(sc.getSocketFactory()), trustManager);

            List<ConnectionSpec> specs = new ArrayList<>();
            specs.add(getModernTls12Spec());
            specs.add(getCompatibleTls12Spec());

            clientBuilder.connectionSpecs(specs);
        } catch (Exception ex) {
            Timber.e(ex, "enableTls12(): Error while setting TLS 1.2");
        }
    }
    return clientBuilder;
}
 
Example 6
Source File: SecureSslContextFactory.java    From openAGV with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an instance of {@link SSLContext} for the client.
 *
 * @return The ssl context.
 * @throws IllegalStateException If the creation of the ssl context fails.
 */
public SSLContext createClientContext()
    throws IllegalStateException {
  SSLContext context = null;

  try {
    KeyStore ts = KeyStore.getInstance(sslParameterSet.getKeystoreType());
    ts.load(new FileInputStream(sslParameterSet.getTruststoreFile()),
            sslParameterSet.getTruststorePassword().toCharArray());
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(KEY_TRUST_MANAGEMENT_ALGORITHM);
    tmf.init(ts);

    context = SSLContext.getInstance(SSL_CONTEXT_PROTOCOL);
    context.init(null, tmf.getTrustManagers(), null);
  }
  catch (NoSuchAlgorithmException | KeyStoreException | CertificateException | IOException
             | KeyManagementException ex) {
    throw new IllegalStateException("Error creating the client's ssl context", ex);
  }

  return context;
}
 
Example 7
Source File: EwsX509TrustManager.java    From ews-java-api with MIT License 6 votes vote down vote up
/**
 * Constructor for EasyX509TrustManager.
 */
public EwsX509TrustManager(KeyStore keystore, TrustManager trustManager)
    throws NoSuchAlgorithmException, KeyStoreException {
  super();
  if (trustManager == null) {
    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];
  } else {
    standardTrustManager = (X509TrustManager) trustManager;
  }
}
 
Example 8
Source File: ExternalMgmtSaslTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Get the trust manager for {@link #CLIENT_TRUSTSTORE_FILE}.
 *
 * @return the trust manager
 */
private static X509TrustManager getTrustManager() throws Exception {
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(loadKeyStore(CLIENT_TRUSTSTORE_FILE));

    for (TrustManager current : trustManagerFactory.getTrustManagers()) {
        if (current instanceof X509TrustManager) {
            return (X509TrustManager) current;
        }
    }

    throw new IllegalStateException("Unable to obtain X509TrustManager.");
}
 
Example 9
Source File: WebServiceClient.java    From nextreports-server with Apache License 2.0 5 votes vote down vote up
protected SavingTrustManager createTrustManager() throws Exception {
	InputStream in = new FileInputStream(keystoreFile);
	ks = KeyStore.getInstance(KeyStore.getDefaultType());
	ks.load(in, keyStorePass.toCharArray());
	in.close();				
	TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
	tmf.init(ks);
	X509TrustManager defaultTrustManager = (X509TrustManager)tmf.getTrustManagers()[0];
	SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);		
	return tm;
}
 
Example 10
Source File: ServerCertificateManager.java    From revolution-irc with GNU General Public License v3.0 5 votes vote down vote up
public static X509TrustManager createKeyStoreTrustManager(KeyStore keyStore) {
    try {
        TrustManagerFactory factory = TrustManagerFactory.getInstance(
                TrustManagerFactory.getDefaultAlgorithm());
        factory.init(keyStore);
        for (TrustManager manager : factory.getTrustManagers()) {
            if (manager instanceof X509TrustManager)
                return (X509TrustManager) manager;
        }
    } catch (NoSuchAlgorithmException | KeyStoreException e) {
        throw new RuntimeException(e);
    }
    return null;
}
 
Example 11
Source File: NanoHTTPD.java    From AndroidHttpServer with MIT License 5 votes vote down vote up
/**
 * Creates an SSLSocketFactory for HTTPS. Pass a loaded KeyStore and an
 * array of loaded KeyManagers. These objects must properly
 * loaded/initialized by the caller.
 */
public static SSLServerSocketFactory makeSSLSocketFactory(KeyStore loadedKeyStore, KeyManager[] keyManagers) throws IOException {
    SSLServerSocketFactory res = null;
    try {
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(loadedKeyStore);
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(keyManagers, trustManagerFactory.getTrustManagers(), null);
        res = ctx.getServerSocketFactory();
    } catch (Exception e) {
        throw new IOException(e.getMessage());
    }
    return res;
}
 
Example 12
Source File: HttpsUtils.java    From ucar-weex-core with Apache License 2.0 5 votes vote down vote up
public MyTrustManager(X509TrustManager localTrustManager) throws NoSuchAlgorithmException, KeyStoreException
{
    TrustManagerFactory var4 = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    var4.init((KeyStore) null);
    defaultTrustManager = chooseTrustManager(var4.getTrustManagers());
    this.localTrustManager = localTrustManager;
}
 
Example 13
Source File: HttpRetrofit.java    From GankGirl with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * 绑定证书
 *
 * @param context      上下文
 * @param certificates 证书源
 * @return
 */
private static SSLSocketFactory getSSLSocketFactory(Context context, int[] certificates) {
    if (context == null) {
        throw new NullPointerException("context == null");
    }

    try {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, null);

        for (int i = 0; i < certificates.length; i++) {
            InputStream certificate = context.getResources().openRawResource(certificates[i]);
            keyStore.setCertificateEntry(String.valueOf(i), certificateFactory.generateCertificate(certificate));
            if (certificate != null) {
                certificate.close();
            }
        }
        SSLContext sslContext = SSLContext.getInstance("TLS");
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);
        sslContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());
        return sslContext.getSocketFactory();
    } catch (CertificateException | KeyStoreException | IOException | NoSuchAlgorithmException | KeyManagementException e) {
        throw new AssertionError(e);
    }
}
 
Example 14
Source File: HttpsUtils.java    From UltimateAndroid with Apache License 2.0 5 votes vote down vote up
/**
 * Build SSLSocketFactory using certificate InputStream
 * @param certificates
 * @param key
 * @param keyPassword
 * @return
 * @throws NoSuchAlgorithmException
 * @throws KeyStoreException
 * @throws KeyManagementException
 * @throws CertificateException
 * @throws IOException
 */
public static SSLSocketFactory getSSLSocketFactory(InputStream certificates, InputStream key, String keyPassword) throws NoSuchAlgorithmException,
        KeyStoreException, KeyManagementException, CertificateException, IOException {


    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    InputStream caInput = new BufferedInputStream(certificates);
    Certificate ca;
    try {
        ca = cf.generateCertificate(caInput);
    } finally {
        caInput.close();
    }

    // Create a KeyStore containing our trusted CAs
    String keyStoreType = KeyStore.getDefaultType();
    KeyStore keyStore = KeyStore.getInstance(keyStoreType);
    keyStore.load(null, null);
    keyStore.setCertificateEntry("ca", ca);

    KeyManagerFactory kmf = null;
    if (key != null && keyPassword != null) {
        kmf = getKeyManagerFactory(key, keyPassword);
    }
    // Create a TrustManager that trusts the CAs in our KeyStore
    String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
    tmf.init(keyStore);

    // Create an SSLContext that uses our TrustManager
    SSLContext contexts = SSLContext.getInstance("TLS");
    contexts.init(kmf == null ? null : kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    return contexts.getSocketFactory();

}
 
Example 15
Source File: EasyX509TrustManager.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Constructor for EasyX509TrustManager.
 */
public EasyX509TrustManager(KeyStore keystore) throws NoSuchAlgorithmException, KeyStoreException {
    super();
    TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    factory.init(keystore);
    TrustManager[] trustmanagers = factory.getTrustManagers();
    if (trustmanagers.length == 0) {
        throw new NoSuchAlgorithmException("no trust manager found");
    }
    this.standardTrustManager = (X509TrustManager) trustmanagers[0];
}
 
Example 16
Source File: TlsOkHttpClientBuilder.java    From besu with Apache License 2.0 5 votes vote down vote up
private TrustManagerFactory getTrustManagerFactory() {
  try {
    final KeyStore trustStore =
        KeyStore.getInstance(
            besuCertificate.getTrustStoreFile().toFile(), besuCertificate.getPassword());
    final TrustManagerFactory trustManagerFactory =
        TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(trustStore);
    return trustManagerFactory;
  } catch (final IOException | GeneralSecurityException e) {
    throw new RuntimeException("Unable to load trust manager factory", e);
  }
}
 
Example 17
Source File: CertificateStreamProvider.java    From openshift-ping with Apache License 2.0 5 votes vote down vote up
static TrustManager[] configureCaCert(String caCertFile) throws Exception {
    if (caCertFile != null) {
        try {
            InputStream pemInputStream = openFile(caCertFile);
            CertificateFactory certFactory = CertificateFactory.getInstance("X509");

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

            Collection<? extends Certificate> certificates = certFactory.generateCertificates(pemInputStream);
            for (Certificate c : certificates) {
                X509Certificate certificate = (X509Certificate) c;
                String alias = certificate.getSubjectX500Principal().getName();
                trustStore.setCertificateEntry(alias, certificate);
            }

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

            return trustManagerFactory.getTrustManagers();
        } catch (Exception e) {
            log.log(Level.SEVERE, "Could not create trust manager for " + caCertFile, e);
            throw e;
        }
    } else {
        if (log.isLoggable(Level.WARNING)) {
            log.log(Level.WARNING, "ca cert file undefined");
        }
        return InsecureStreamProvider.INSECURE_TRUST_MANAGERS;
    }
}
 
Example 18
Source File: CipherTestUtils.java    From openjdk-jdk8u with 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 19
Source File: TestGRPCServer.java    From nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Starts the gRPC server @localhost:port.
 */
public int start(final int port) throws Exception {
    final NettyServerBuilder nettyServerBuilder = NettyServerBuilder
            .forPort(port)
            .directExecutor()
            .addService(clazz.newInstance())
            .compressorRegistry(CompressorRegistry.getDefaultInstance())
            .decompressorRegistry(DecompressorRegistry.getDefaultInstance());

    if (this.sslProperties != null) {
        if (sslProperties.get(StandardSSLContextService.KEYSTORE.getName()) == null) {
            throw new RuntimeException("You must configure a keystore in order to use SSL with gRPC.");
        }

        final KeyManagerFactory keyManager = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        final KeyStore keyStore = KeyStore.getInstance(sslProperties.get(StandardSSLContextService.KEYSTORE_TYPE.getName()));
        final String keyStoreFile = sslProperties.get(StandardSSLContextService.KEYSTORE.getName());
        final String keyStorePassword = sslProperties.get(StandardSSLContextService.KEYSTORE_PASSWORD.getName());
        try (final InputStream is = new FileInputStream(keyStoreFile)) {
            keyStore.load(is, keyStorePassword.toCharArray());
        }
        keyManager.init(keyStore, keyStorePassword.toCharArray());
        SslContextBuilder sslContextBuilder = SslContextBuilder.forServer(keyManager);

        if (sslProperties.get(StandardSSLContextService.TRUSTSTORE.getName()) != null) {
            final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            final KeyStore trustStore = KeyStore.getInstance(sslProperties.get(StandardSSLContextService.TRUSTSTORE_TYPE.getName()));
            final String trustStoreFile = sslProperties.get(StandardSSLContextService.TRUSTSTORE.getName());
            final String trustStorePassword = sslProperties.get(StandardSSLContextService.TRUSTSTORE_PASSWORD.getName());
            try (final InputStream is = new FileInputStream(trustStoreFile)) {
                trustStore.load(is, trustStorePassword.toCharArray());
            }
            trustManagerFactory.init(trustStore);
            sslContextBuilder = sslContextBuilder.trustManager(trustManagerFactory);
        }

        final String clientAuth = sslProperties.get(NEED_CLIENT_AUTH);
        if (clientAuth == null) {
            sslContextBuilder = sslContextBuilder.clientAuth(ClientAuth.REQUIRE);
        } else {
            sslContextBuilder = sslContextBuilder.clientAuth(ClientAuth.valueOf(clientAuth));
        }
        sslContextBuilder = GrpcSslContexts.configure(sslContextBuilder);
        nettyServerBuilder.sslContext(sslContextBuilder.build());
    }

    server = nettyServerBuilder.build().start();
    final int actualPort = server.getPort();

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            // Use stderr here since the logger may have been reset by its JVM shutdown hook.
            System.err.println("*** shutting down gRPC server since JVM is shutting down");
            TestGRPCServer.this.stop();
            System.err.println("*** server shut down");
        }
    });
    return actualPort;
}
 
Example 20
Source File: TrustManagerTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testOSCPOverride() throws Exception {
    SpringBusFactory bf = new SpringBusFactory();
    URL busFile = TrustManagerTest.class.getResource("client-trust.xml");

    Bus bus = bf.createBus(busFile.toString());
    BusFactory.setDefaultBus(bus);
    BusFactory.setThreadDefaultBus(bus);

    URL url = SOAPService.WSDL_LOCATION;
    SOAPService service = new SOAPService(url, SOAPService.SERVICE);
    assertNotNull("Service is null", service);
    final Greeter port = service.getHttpsPort();
    assertNotNull("Port is null", port);

    updateAddressPort(port, PORT2);

    // Enable Async
    if (async) {
        ((BindingProvider)port).getRequestContext().put("use.async.http.conduit", true);
    }

    // Read truststore
    KeyStore ts = KeyStore.getInstance("JKS");
    try (InputStream trustStore =
        ClassLoaderUtils.getResourceAsStream("keys/cxfca.jks", TrustManagerTest.class)) {
        ts.load(trustStore, "password".toCharArray());
    }

    try {
        Security.setProperty("ocsp.enable", "true");

        PKIXBuilderParameters param = new PKIXBuilderParameters(ts, new X509CertSelector());
        param.setRevocationEnabled(true);

        TrustManagerFactory tmf  =
            TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(new CertPathTrustManagerParameters(param));

        TLSClientParameters tlsParams = new TLSClientParameters();
        tlsParams.setTrustManagers(tmf.getTrustManagers());
        tlsParams.setDisableCNCheck(true);

        Client client = ClientProxy.getClient(port);
        HTTPConduit http = (HTTPConduit) client.getConduit();
        http.setTlsClientParameters(tlsParams);

        try {
            port.greetMe("Kitty");
            fail("Failure expected on an invalid OCSP responder URL");
        } catch (Exception ex) {
            // expected
        }

    } finally {
        Security.setProperty("ocsp.enable", "false");
    }

    ((java.io.Closeable)port).close();
    bus.shutdown(true);
}