Java Code Examples for javax.net.ssl.X509TrustManager

The following examples show how to use javax.net.ssl.X509TrustManager. 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: syndesis   Source File: KeyStoreHelper.java    License: Apache License 2.0 8 votes vote down vote up
public static KeyStore defaultKeyStore()
    throws KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException {

    final KeyStore defaultKeystore = KeyStore.getInstance(KeyStore.getDefaultType());
    defaultKeystore.load(null);

    final TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    factory.init((KeyStore) null);

    for (final TrustManager manager : factory.getTrustManagers()) {
        final X509TrustManager x509Manager = (X509TrustManager) manager;

        final X509Certificate[] issuers = x509Manager.getAcceptedIssuers();
        for (final X509Certificate issuer : issuers) {
            final String alias = issuer.getSerialNumber().toString();
            final TrustedCertificateEntry entry = new TrustedCertificateEntry(issuer);
            defaultKeystore.setEntry(alias, entry, null);
        }
    }

    return defaultKeystore;
}
 
Example 2
Source Project: AndroidHttpCapture   Source File: TrustUtil.java    License: MIT License 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.
 */
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 3
Source Project: FoxTelem   Source File: ExportControlled.java    License: GNU General Public License v3.0 6 votes vote down vote up
public X509TrustManagerWrapper(X509TrustManager tm, boolean verifyServerCertificate, String hostName) throws CertificateException {
    this.origTm = tm;
    this.verifyServerCert = verifyServerCertificate;
    this.hostName = hostName;

    if (verifyServerCertificate) {
        try {
            Set<TrustAnchor> anch = Arrays.stream(tm.getAcceptedIssuers()).map(c -> new TrustAnchor(c, null)).collect(Collectors.toSet());
            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);
        }
    }

}
 
Example 4
Source Project: http4e   Source File: AuthSSLProtocolSocketFactory.java    License: Apache License 2.0 6 votes vote down vote up
private static TrustManager[] createTrustManagers(final KeyStore keystore)
    throws KeyStoreException, NoSuchAlgorithmException
{ 
    if (keystore == null) {
        throw new IllegalArgumentException("Keystore may not be null");
    }
    LOG.debug("Initializing trust manager");
    TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(
        TrustManagerFactory.getDefaultAlgorithm());
    tmfactory.init(keystore);
    TrustManager[] trustmanagers = tmfactory.getTrustManagers();
    for (int i = 0; i < trustmanagers.length; i++) {
        if (trustmanagers[i] instanceof X509TrustManager) {
            trustmanagers[i] = new AuthSSLX509TrustManager(
                (X509TrustManager)trustmanagers[i]); 
        }
    }
    return trustmanagers; 
}
 
Example 5
Source Project: scipio-erp   Source File: TrustManagers.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    for(X509TrustManager tm : startClientTms) {
        try {
            tm.checkClientTrusted(chain, authType);
            return; // first found
        } catch(CertificateException e) {
            ; // proceed
        }
    }
    // last try
    if (finalClientTm == null) {
        throw new CertificateException("Cannot validate client certificate (no delegated trust managers for client check)");
    }
    finalClientTm.checkClientTrusted(chain, authType);
}
 
Example 6
Source Project: cellery-distribution   Source 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 7
Source Project: spring-credhub   Source File: SslCertificateUtils.java    License: Apache License 2.0 6 votes vote down vote up
X509TrustManager getDefaultX509TrustManager() {
	try {
		TrustManagerFactory trustManagerFactory = TrustManagerFactory
				.getInstance(TrustManagerFactory.getDefaultAlgorithm());
		trustManagerFactory.init((KeyStore) null);

		TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();

		for (TrustManager trustManager : trustManagers) {
			if (trustManager instanceof X509TrustManager) {
				return (X509TrustManager) trustManager;
			}
		}

		throw new IllegalStateException(
				"Unable to setup SSL; no X509TrustManager found in: " + Arrays.toString(trustManagers));
	}
	catch (GeneralSecurityException ex) {
		throw new IllegalStateException("Unable to setup SSL; error getting a X509TrustManager: " + ex.getMessage(),
				ex);
	}
}
 
Example 8
Source Project: TrustKit-Android   Source File: TrustManagerBuilder.java    License: MIT License 6 votes vote down vote up
public static X509TrustManager getTrustManager(@NonNull String serverHostname) {
    if (baselineTrustManager == null) {
        throw new IllegalStateException("TrustManagerBuilder has not been initialized");
    }
    if (Build.VERSION.SDK_INT < 17) {
        // No pinning validation at all for API level before 17
        // Because X509TrustManagerExtensions is not available
        return baselineTrustManager;
    }

    // Get the pinning policy for this hostname
    DomainPinningPolicy serverConfig =
            TrustKit.getInstance().getConfiguration().getPolicyForHostname(serverHostname);
    if ((serverConfig == null) || (shouldOverridePins)) {
        // Domain is NOT pinned or there is a debug override - only do baseline validation
        return baselineTrustManager;
    } else {
        return new PinningTrustManager(serverHostname, serverConfig, baselineTrustManager);
    }
}
 
Example 9
/**
 * 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 10
Source Project: omise-java   Source File: Client.java    License: MIT License 6 votes vote down vote up
/**
 * Returns a new {@link OkHttpClient} to use for performing {@link Request}(s). Override this to customize the HTTP
 * client. This method will be called once during construction and the result will be cached internally.
 * <p>
 * It is generally a good idea to implement this by adding to the builder created from
 * <code>super.buildHttpClient(config).newBuilder()</code> so that all configurations are properly applied and SSL
 * certificates are pinned.
 * </p>
 *
 * @param config A {@link Config} object built from constructor parameters.
 * @return A new {@link OkHttpClient} object for connecting to the Omise API.
 * @throws ClientException if client configuration fails (e.g. when TLSv1.2 is not supported)
 */
protected OkHttpClient buildHttpClient(Config config) throws ClientException {
    SSLContext sslContext;
    X509TrustManager trustManager;
    try {
        sslContext = SSLContext.getInstance("TLSv1.2");
        sslContext.init(null, null, null);

        trustManager = getX509TrustManager();
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
        throw new ClientException(e);
    }

    ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
            .tlsVersions(TlsVersion.TLS_1_2)
            .build();

    return new OkHttpClient.Builder()
            .sslSocketFactory(sslContext.getSocketFactory(), trustManager)
            .addInterceptor(new Configurer(config))
            .connectionSpecs(Collections.singletonList(spec))
            .readTimeout(60, TimeUnit.SECONDS)
            .build();
}
 
Example 11
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()]);
}
 
Example 12
Source Project: armeria   Source File: UpstreamSimpleBenchmark.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected SimpleBenchmarkClient newClient() throws Exception {
    final SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, InsecureTrustManagerFactory.INSTANCE.getTrustManagers(), null);
    final OkHttpClient client = new OkHttpClient.Builder()
            .sslSocketFactory(context.getSocketFactory(),
                              (X509TrustManager) InsecureTrustManagerFactory.INSTANCE.getTrustManagers()[0])
            .hostnameVerifier((s, session) -> true)
            .build();

    return new Retrofit.Builder()
            .baseUrl(baseUrl())
            .client(client)
            .addConverterFactory(JacksonConverterFactory.create())
            .build()
            .create(SimpleBenchmarkClient.class);
}
 
Example 13
Source Project: trufflesqueak   Source File: SSLContextInitializer.java    License: MIT License 6 votes vote down vote up
@Override
public void checkServerTrusted(final X509Certificate[] chain, final String authType)
                throws CertificateException {

    CertificateException lastError = null;
    for (final X509TrustManager manager : managers) {
        try {
            manager.checkServerTrusted(chain, authType);
            return;
        } catch (final CertificateException e) {
            lastError = e;
        }
    }

    if (lastError != null) {
        throw lastError;
    }
}
 
Example 14
Source Project: netty-4.1.22   Source File: SimpleTrustManagerFactory.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected TrustManager[] engineGetTrustManagers() {
    TrustManager[] trustManagers = this.trustManagers;
    if (trustManagers == null) {
        trustManagers = parent.engineGetTrustManagers();
        if (PlatformDependent.javaVersion() >= 7) {
            for (int i = 0; i < trustManagers.length; i++) {
                final TrustManager tm = trustManagers[i];
                if (tm instanceof X509TrustManager && !(tm instanceof X509ExtendedTrustManager)) {
                    trustManagers[i] = new X509TrustManagerWrapper((X509TrustManager) tm);
                }
            }
        }
        this.trustManagers = trustManagers;
    }
    return trustManagers.clone();
}
 
Example 15
Source Project: incubator-tuweni   Source File: TrustManagerFactories.java    License: Apache License 2.0 5 votes vote down vote up
private static TrustManagerFactory wrap(X509TrustManager trustManager, @Nullable TrustManagerFactory delegate) {
  if (delegate != null) {
    return new DelegatingTrustManagerFactory(delegate, trustManager);
  } else {
    return new SingleTrustManagerFactory(trustManager);
  }
}
 
Example 16
Source Project: Dream-Catcher   Source File: TrustUtil.java    License: MIT License 5 votes vote down vote up
@Override
public X509Certificate[] get() {
    X509TrustManager defaultTrustManager = getDefaultJavaTrustManager();

    X509Certificate[] defaultJavaTrustedCerts = defaultTrustManager.getAcceptedIssuers();

    if (defaultJavaTrustedCerts != null) {
        return defaultJavaTrustedCerts;
    } else {
        return EMPTY_CERTIFICATE_ARRAY;
    }
}
 
Example 17
public ApacheSSLSocketFactory(KeyStore keyStore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
    super(keyStore);

    try {
        this.mSSLContext = SSLContext.getInstance("TLS");
    } catch (Exception e) {
        this.mSSLContext = SSLContext.getInstance("LLS");
    }

    this.mSSLContext.init(null,
            new X509TrustManager[]{new SimpleX509TrustManager()},
            null);
}
 
Example 18
Source Project: alpha-wallet-android   Source File: XMLDSigVerifier.java    License: MIT License 5 votes vote down vote up
private void validateCertificateChain(List<X509Certificate> certList)
        throws NoSuchAlgorithmException,
        KeyStoreException,
        InvalidAlgorithmParameterException,
        CertificateException,
        CertPathValidatorException
{
    // By default on Oracle JRE, algorithm is PKIX
    TrustManagerFactory tmf = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    // 'null' will initialise the tmf with the default CA certs installed
    // with the JRE.
    tmf.init((KeyStore) null);

    X509TrustManager tm = (X509TrustManager) tmf.getTrustManagers()[0];
    CertPathValidator cpv = CertPathValidator.getInstance("PKIX");
    Set<TrustAnchor> anch = new HashSet<>();
    for (X509Certificate cert : tm.getAcceptedIssuers())
    {
        anch.add(new TrustAnchor(cert, null));
    }
    PKIXParameters params = new PKIXParameters(anch);
    Security.setProperty("ocsp.enable", "true");
    params.setRevocationEnabled(true);
    CertificateFactory factory = CertificateFactory.getInstance("X.509");
    try
    {
        cpv.validate(factory.generateCertPath(certList), params);
    }
    catch (CertPathValidatorException e)
    {
        System.out.println(e.getIndex());
        //if the timestamp check fails because the cert is expired
        //we allow this to continue (code 0)
        if(e.getIndex() != 0)
        {
            throw e;
        }
    }
}
 
Example 19
Source Project: Focus   Source File: HttpsUtil.java    License: GNU General Public License v3.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 20
Source Project: CapturePacket   Source 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));
}
 
Example 21
Source Project: okhttputils   Source File: HttpsUtils.java    License: 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 22
Source Project: phoebus   Source File: DummyX509TrustManager.java    License: Eclipse Public License 1.0 5 votes vote down vote up
DummyX509TrustManager(File trustStore, char[] password) throws Exception {
	// create a "default" JSSE X509TrustManager.
	KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());

	ks.load(new FileInputStream(trustStore), password);

	TrustManagerFactory tmf = TrustManagerFactory
			.getInstance(TrustManagerFactory.getDefaultAlgorithm());
	tmf.init(ks);

	TrustManager tms[] = tmf.getTrustManagers();

	/*
	 * Iterate over the returned trustmanagers, look for an instance of
	 * X509TrustManager. If found, use that as our "default" trust manager.
	 */
	for (int i = 0; i < tms.length; i++) {
		if (tms[i] instanceof X509TrustManager) {
			pkixTrustManager = (X509TrustManager) tms[i];
			return;
		}
	}

	/*
	 * Find some other way to initialize, or else we have to fail the
	 * constructor.
	 */
	throw new Exception("Couldn't initialize");
}
 
Example 23
Source Project: razorpay-java   Source File: ApiUtils.java    License: MIT License 5 votes vote down vote up
private static X509TrustManager createDefaultTrustManager() throws NoSuchAlgorithmException, KeyStoreException {
  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];
  return trustManager;
}
 
Example 24
Source Project: anthelion   Source File: DummyX509TrustManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Constructor for DummyX509TrustManager.
 */
public DummyX509TrustManager(KeyStore keystore) throws NoSuchAlgorithmException, KeyStoreException {
    super();
    String algo = TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory factory = TrustManagerFactory.getInstance(algo);
    factory.init(keystore);
    TrustManager[] trustmanagers = factory.getTrustManagers();
    if (trustmanagers.length == 0) {
        throw new NoSuchAlgorithmException(algo + " trust manager not supported");
    }
    this.standardTrustManager = (X509TrustManager)trustmanagers[0];
}
 
Example 25
/**
 * Return the list of accepted issuers for this trust manager.
 *
 * @return array of accepted issuers
 */
public synchronized X509Certificate[] getAcceptedIssuers()
{
    List<X509Certificate> certificates = new ArrayList<>();
    
    for ( X509TrustManager trustManager : x509TrustManagers )
    {
        for ( X509Certificate certificate : trustManager.getAcceptedIssuers() )
        { 
            certificates.add( certificate );
        }
    }
        
    return certificates.toArray( new X509Certificate[]{} );
}
 
Example 26
private void setTrustManager() throws IOException, GeneralSecurityException {
  TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
  tmf.init(ks);
  for (TrustManager tm : tmf.getTrustManagers()) {
    if (tm instanceof X509TrustManager) {
      trustManager = (X509TrustManager) tm;
      break;
    }
  }
  if (trustManager == null) {
    throw new GeneralSecurityException("No X509TrustManager found");
  }
}
 
Example 27
Source Project: ache   Source File: OkHttpFetcher.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns the VM's default SSL socket factory, using {@code trustManager} for trusted root
 * certificates.
 */
private static SSLSocketFactory defaultSslSocketFactory(X509TrustManager trustManager)
        throws NoSuchAlgorithmException, KeyManagementException {
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, new TrustManager[] { trustManager }, null);

    return sslContext.getSocketFactory();
}
 
Example 28
/**
 * 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 29
Source Project: lorne_core   Source File: EasyX509TrustManager.java    License: Apache 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 30
@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");
}