javax.net.ssl.X509TrustManager Java Examples

The following examples show how to use javax.net.ssl.X509TrustManager. 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: KeyStoreHelper.java    From syndesis with Apache License 2.0 10 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 File: SSLContextInitializer.java    From trufflesqueak with MIT License 7 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 #3
Source File: KeyStoresTrustManager.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 6 votes vote down vote up
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 #4
Source File: TrustManagerBuilder.java    From TrustKit-Android with 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 #5
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 #6
Source File: AuthSSLProtocolSocketFactory.java    From http4e with 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 #7
Source File: UpstreamSimpleBenchmark.java    From armeria with 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 #8
Source File: SslCertificateUtils.java    From spring-credhub with 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 #9
Source File: TrustManagers.java    From scipio-erp with 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 #10
Source File: ExportControlled.java    From FoxTelem with 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 #11
Source File: SimpleTrustManagerFactory.java    From netty-4.1.22 with 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 #12
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 #13
Source File: Client.java    From omise-java with 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 #14
Source File: TrustUtil.java    From AndroidHttpCapture with 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 #15
Source File: CompositeX509TrustManager.java    From zap-extensions with Apache License 2.0 5 votes vote down vote up
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
	for (X509TrustManager trustManager : trustManagers) {
		try {
			trustManager.checkServerTrusted(chain, authType);
			return; // someone trusts them. success!
		} catch (CertificateException e) {
			// maybe someone else will trust them
		}
	}
	throw new CertificateException("None of the TrustManagers trust this certificate chain");
}
 
Example #16
Source File: CipherTestUtils.java    From dragonwell8_jdk 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 #17
Source File: TrustManagerFactories.java    From cava with 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 #18
Source File: HttpsUtils.java    From DoraemonKit 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 #19
Source File: SOAPClientConnectConfig.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
protected X509TrustManager makeTrustManager(CertCheckConfig certCheckConfig, boolean log) {
    if (certCheckConfig != null) {
        DelegatingTrustManager tm = (DelegatingTrustManager) TrustManagers.getDelegatingTrustManager(certCheckConfig);
        if (log) {
            Debug.logInfo("SOAP config: Created DelegatingTrustManager for SOAP certificate validation: " + tm, module);
        }
        return tm;
    } else {
        if (log) {
            Debug.logWarning("SOAP config: Missing or broken " + propResource + ".properties " + certPropPrefix+"validate.* configuration"
                    + "; cannot create DelegatingTrustManager; using TrustNooneManager (all certs will be rejected until configuration is fixed)", module);
        }
        return TrustManagers.getTrustNooneManager();
    }
}
 
Example #20
Source File: SSLUtil.java    From strimzi-kafka-oauth with Apache License 2.0 5 votes vote down vote up
private static X509TrustManager getTrustManager(TrustManagerFactory tmf) {
    for (TrustManager tm : tmf.getTrustManagers()) {
        if (tm instanceof X509TrustManager) {
            return (X509TrustManager) tm;
        }
    }
    throw new IllegalStateException("No X509TrustManager on default factory");
}
 
Example #21
Source File: SSLContextInitializer.java    From trufflesqueak with MIT License 5 votes vote down vote up
@Override
public X509Certificate[] getAcceptedIssuers() {
    final List<X509Certificate> certificates = new ArrayList<>();
    for (final X509TrustManager manager : managers) {
        certificates.addAll(asList(manager.getAcceptedIssuers()));
    }
    return certificates.toArray(new X509Certificate[0]);
}
 
Example #22
Source File: CipherTestUtils.java    From openjdk-jdk8u-backup 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 #23
Source File: PartialTrustManager.java    From drftpd with GNU General Public License v2.0 5 votes vote down vote up
public void checkServerTrusted(X509Certificate[] chain, String authType)
        throws CertificateException {
    for (TrustManager manager : _defaultManagers) {
        if (manager instanceof X509TrustManager) {
            X509TrustManager x509Manager = (X509TrustManager) manager;
            x509Manager.checkServerTrusted(chain, authType);
        }
    }
}
 
Example #24
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 #25
Source File: TrustManagers.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
@Override
public X509TrustManager getTrustManager() {
    try {
        KeyStore keystore = KeyStoreUtil.getStore(keystoreFile, keystorePass, keystoreType);
        return getKeyStoreTrustManager(keystore);
    } catch (Exception e) {
        Debug.logError(e, "Could not load keystore '" + keystoreFile + "': " + e.getMessage(), module);
        return null;
    }
}
 
Example #26
Source File: DefaultX509TrustManager.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor for DefaultX509TrustManager.
 * 
 */
public DefaultX509TrustManager(KeyStore keystore) throws NoSuchAlgorithmException, KeyStoreException {
    super();

    TrustManagerFactory factory = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    factory.init(keystore);

    TrustManager[] trustmanagers = factory.getTrustManagers();

    if (trustmanagers.length == 0) {
        throw new NoSuchAlgorithmException("SunX509 trust manager not supported");
    }

    this.standardTrustManager = (X509TrustManager) trustmanagers[0];
}
 
Example #27
Source File: FileTrustStoreSslSocketFactory.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@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");
}
 
Example #28
Source File: EasyX509TrustManager.java    From lorne_core with 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 #29
Source File: ReloadingX509TrustManager.java    From big-c with Apache License 2.0 5 votes vote down vote up
@Override
public X509Certificate[] getAcceptedIssuers() {
  X509Certificate[] issuers = EMPTY;
  X509TrustManager tm = trustManagerRef.get();
  if (tm != null) {
    issuers = tm.getAcceptedIssuers();
  }
  return issuers;
}
 
Example #30
Source File: EasyX509TrustManager.java    From openemm with GNU Affero General Public License v3.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];
}