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

The following examples show how to use javax.net.ssl.TrustManagerFactory#getTrustManagers() . 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: HttpWebConnectionInsecureSSLWithClientCertificateTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if an error occurs
 */
@Before
public void setUp() throws Exception {
    final URL url = getClass().getClassLoader().getResource("insecureSSL.keystore");
    final KeyStore keystore = KeyStore.getInstance("jks");
    final char[] pwd = "nopassword".toCharArray();
    keystore.load(url.openStream(), pwd);

    final TrustManagerFactory trustManagerFactory = createTrustManagerFactory();
    trustManagerFactory.init(keystore);
    final TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();

    final KeyManagerFactory keyManagerFactory = createKeyManagerFactory();
    keyManagerFactory.init(keystore, pwd);
    final KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();

    final SSLContext serverSSLContext = SSLContext.getInstance("TLS");
    serverSSLContext.init(keyManagers, trustManagers, null);

    localServer_ = new LocalTestServer(serverSSLContext);
    localServer_.start();
}
 
Example 2
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 3
Source File: CelleryTrustManager.java    From cellery-security with Apache License 2.0 6 votes vote down vote up
private void findDefaultTrustManager() throws CelleryCellSTSException {

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

            for (int i = 0; i < trustManagers.length; i++) {
                TrustManager t = trustManagers[i];
                if (t instanceof X509TrustManager) {
                    this.defaultTrustManager = (X509TrustManager) t;
                    return;
                }
            }
        } catch (NoSuchAlgorithmException | KeyStoreException e) {
            throw new CelleryCellSTSException("Error while setting trust manager", e);
        }
        throw new CelleryCellSTSException("No registered trust manager found");
    }
 
Example 4
Source File: EasyX509TrustManager.java    From cs-actions with Apache License 2.0 6 votes vote down vote up
public EasyX509TrustManager() throws NoSuchAlgorithmException, KeyStoreException {
    super();
    TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    try {
        factory.init((KeyStore) null);
        TrustManager[] trustManagers = factory.getTrustManagers();
        if (trustManagers.length == 0) {
            throw new NoSuchAlgorithmException("SunX509 trust manager not supported");
        }
        this.standardTrustManager = (X509TrustManager) trustManagers[0];
    } catch (Exception ex) {
        if(!ex.getMessage().contains("problem accessing trust store")) {
            throw ex;
        }
    }
}
 
Example 5
Source File: NetUtils.java    From Aria2App with GNU General Public License v3.0 6 votes vote down vote up
public static void setSslSocketFactory(@NonNull OkHttpClient.Builder builder, @NonNull Certificate ca) throws GeneralSecurityException, IOException {
    char[] password = "password".toCharArray();
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(null, password);
    keyStore.setCertificateEntry("ca", ca);

    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, password);
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(keyStore);
    TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
    if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager))
        throw new GeneralSecurityException("Unexpected default trust managers:" + Arrays.toString(trustManagers));

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, new TrustManager[]{trustManagers[0]}, null);
    SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

    builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustManagers[0]);
}
 
Example 6
Source File: DefaultX509TrustManager.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
public DefaultX509TrustManager init() throws IOException {
    try {
        final TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        factory.init(KeyStore.getInstance(KeyStore.getDefaultType()));
        final TrustManager[] trustmanagers = factory.getTrustManagers();
        if(trustmanagers.length == 0) {
            throw new NoSuchAlgorithmException("SunX509 trust manager not supported");
        }
        system = (javax.net.ssl.X509TrustManager) trustmanagers[0];
    }
    catch(NoSuchAlgorithmException | KeyStoreException e) {
        log.error(String.format("Initialization of trust store failed. %s", e.getMessage()));
        throw new IOException(e);
    }
    return this;
}
 
Example 7
Source File: KeyStoreUtil.java    From apiman with Apache License 2.0 6 votes vote down vote up
/**
 * Gets an array of trust managers for a given store+password.
 *
 * @param pathInfo
 * @return
 * @throws Exception
 */
public static TrustManager[] getTrustManagers(Info pathInfo) throws Exception {
    File trustStoreFile = new File(pathInfo.store);
    if (!trustStoreFile.isFile()) {
        throw new Exception("No TrustManager: " + pathInfo.store + " does not exist.");
    }
    String trustStorePassword = pathInfo.password;
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    KeyStore truststore = KeyStore.getInstance("JKS");

    FileInputStream fis = new FileInputStream(pathInfo.store);
    truststore.load(fis, trustStorePassword.toCharArray());
    fis.close();
    tmf.init(truststore);
    return tmf.getTrustManagers();
}
 
Example 8
Source File: NFSeGeraCadeiaCertificados.java    From nfse with MIT License 5 votes vote down vote up
public static void get(String host, int port, KeyStore keyStore) throws Exception {
  TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
  tmf.init(keyStore);
  
  X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
  SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
  
  SSLContext sslContext = SSLContext.getInstance("TLS");
  sslContext.init(null, new TrustManager[] {tm}, null);
  
  LOGGER.info("Iniciando conexão com: " + host + ":" + port + "...");
  SSLSocket socket = (SSLSocket) sslContext.getSocketFactory().createSocket(host, port);
  
  try {
    socket.setSoTimeout(30 * 1000);
    socket.startHandshake();
    socket.close();
  } catch (Exception e) {
    LOGGER.info(e.toString());
  } 

  X509Certificate[] chain = tm.chain;
  if (chain == null) {
    LOGGER.info("Não foi possivel obter a cadeia de certificados");
  }

  LOGGER.info("O servidor enviou " + chain.length + " certificado(s):");
  MessageDigest sha1 = MessageDigest.getInstance("SHA1");
  MessageDigest md5 = MessageDigest.getInstance("MD5");
  for (int i = 0; i < chain.length; i++) {
    X509Certificate cert = chain[i];
    sha1.update(cert.getEncoded());
    md5.update(cert.getEncoded());

    String alias = host + "-" + (i);
    keyStore.setCertificateEntry(alias, cert);
    LOGGER.info("Certificado adicionado usando alias: '" + alias + "'");
  }
}
 
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: TrustManagerUtils.java    From vespa with Apache License 2.0 5 votes vote down vote up
public static X509ExtendedTrustManager createDefaultX509TrustManager(KeyStore truststore) {
    try {
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(truststore);
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
        return Arrays.stream(trustManagers)
                .filter(manager -> manager instanceof X509ExtendedTrustManager)
                .map(X509ExtendedTrustManager.class::cast)
                .findFirst()
                .orElseThrow(() -> new RuntimeException("No X509ExtendedTrustManager in " + com.yahoo.vespa.jdk8compat.List.of(trustManagers)));
    } catch (GeneralSecurityException e) {
        throw new RuntimeException(e);
    }
}
 
Example 11
Source File: CustomTrustManager.java    From Dayon with GNU General Public License v3.0 5 votes vote down vote up
private X509TrustManager getDefaultX509TrustManager(TrustManagerFactory tmf) throws NoSuchAlgorithmException {
	for (TrustManager tm : tmf.getTrustManagers()) {
		if (tm instanceof X509TrustManager) {
			return (X509TrustManager) tm;
		}
	}
	throw new NoSuchAlgorithmException();
}
 
Example 12
Source File: DummyX509TrustManager.java    From anthelion with 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 13
Source File: KeyStoreUtil.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
public static TrustManager[] createTrustManagers(final KeyStore keystore) {
  try {
    TrustManagerFactory tmfactory =
        TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmfactory.init(keystore);
    TrustManager[] trustmanagers = tmfactory.getTrustManagers();
    return trustmanagers;
  } catch (Exception e) {
    throw new IllegalArgumentException("Bad trust store."
        + e.getMessage());
  }
}
 
Example 14
Source File: EasyX509TrustManager.java    From olat 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("SunX509");
    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 15
Source File: SslCertificateTrusterTest.java    From cloudfoundry-certificate-truster with Apache License 2.0 5 votes vote down vote up
@Test
public void appendToTruststore() throws Exception {
	// get self-signed cert
	KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
	String password = "changeit";
	keystore.load(SslCertificateTrusterTest.class.getResourceAsStream("/selfsigned.jks"), password.toCharArray());
	X509Certificate selfsigned = (X509Certificate) keystore.getCertificate("mykey");

	SslCertificateTruster.appendToTruststore(new X509Certificate[] { selfsigned });

	// verify defaultTrustManager contains cert
	TrustManagerFactory trustManagerFactory =
			TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
	// this will initialize with the first valid keystore
	// 1. javax.net.ssl.trustStore
	// 2. jssecerts
	// 3. cacerts
	// see https://github.com/openjdk-mirror/jdk7u-jdk/blob/master/src/share/classes/sun/security/ssl/TrustManagerFactoryImpl.java#L130
	trustManagerFactory.init((KeyStore) null);
	X509TrustManager defaultTrustManager = (X509TrustManager) trustManagerFactory.getTrustManagers()[0];
	X509Certificate[] cacerts = defaultTrustManager.getAcceptedIssuers();
	for (X509Certificate certificate : cacerts) {
		if (certificate.getSubjectDN().equals(selfsigned.getSubjectDN())) {
			return;
		}
	}
	Assert.fail();
}
 
Example 16
Source File: Client.java    From omise-java with MIT License 5 votes vote down vote up
/**
 * Gets x509 trust manager.
 *
 * @return the x509 trust manager
 * @throws KeyStoreException        the key store exception
 * @throws NoSuchAlgorithmException the no such algorithm exception
 */
protected X509TrustManager getX509TrustManager() throws KeyStoreException, NoSuchAlgorithmException {
    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));
    }

    return (X509TrustManager) trustManagers[0];
}
 
Example 17
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 18
Source File: ProxyClientUtil.java    From secrets-proxy with Apache License 2.0 5 votes vote down vote up
public static TrustManager[] getTrustManagers(OneOpsConfig.TrustStore config)
    throws GeneralSecurityException {
  final TrustManagerFactory trustManagerFactory =
      TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
  trustManagerFactory.init(keyStoreFromResource(config));
  return trustManagerFactory.getTrustManagers();
}
 
Example 19
Source File: SecurityServiceImpl.java    From gvnix with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Get certificates in the chain of the host server and import them.
 * <p>
 * Tries to get the certificates in the certificates chain of the host
 * server and import them to:
 * <ol>
 * <li>A custom keystore in <code>SRC_MAIN_RESOURCES/gvnix-cacerts</code></li>
 * <li>The JVM cacerts keystore in
 * <code>$JAVA_HOME/jre/lib/security/cacerts</code>. Here we can have a
 * problem if JVM <code>cacerts</code> file is not writable by the user due
 * to file permissions. In this case we throw an exception informing about
 * the error.</li>
 * </ol>
 * </p>
 * <p>
 * With that operation we can try again to get the WSDL.<br/>
 * Also it exports the chain certificates to <code>.cer</code> files in
 * <code>SRC_MAIN_RESOURCES</code>, so the developer can distribute them for
 * its installation in other environments or just in case we reach the
 * problem with the JVM <code>cacerts</code> file permissions.
 * </p>
 * 
 * @see GvNix509TrustManager#saveCertFile(String, X509Certificate,
 *      FileManager, PathResolver)
 * @see <a href=
 *      "http://download.oracle.com/javase/6/docs/technotes/tools/solaris/keytool.html"
 *      >Java SE keytool</a>.
 */
protected Document installCertificates(String loc, String pass)
        throws NoSuchAlgorithmException, KeyStoreException, Exception,
        KeyManagementException, MalformedURLException, IOException,
        UnknownHostException, SocketException, SAXException {

    // Create a SSL context
    SSLContext context = SSLContext.getInstance("TLS");
    TrustManagerFactory tmf = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());

    // Passphrase of the keystore: "changeit" by default
    char[] passArray = (StringUtils.isNotBlank(pass) ? pass.toCharArray()
            : "changeit".toCharArray());

    // Get the project keystore and copy it from JVM if not exists
    File keystore = getProjectKeystore();

    tmf.init(GvNix509TrustManager.loadKeyStore(keystore, passArray));

    X509TrustManager defaultTrustManager = (X509TrustManager) tmf
            .getTrustManagers()[0];
    GvNix509TrustManager tm = new GvNix509TrustManager(defaultTrustManager);
    context.init(null, new TrustManager[] { tm }, null);
    SSLSocketFactory factory = context.getSocketFactory();

    // Open URL location (default 443 port if not defined)
    URL url = new URL(loc);
    String host = url.getHost();
    int port = url.getPort() == -1 ? 443 : url.getPort();
    SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
    socket.setSoTimeout(10000);

    Document doc = null;
    try {

        socket.startHandshake();
        URLConnection connection = url.openConnection();
        if (connection instanceof HttpsURLConnection) {
            ((HttpsURLConnection) connection).setSSLSocketFactory(factory);
        }

        doc = XmlUtils.getDocumentBuilder().parse(
                connection.getInputStream());

        socket.close();

    }
    catch (SSLException ssle) {

        // Get needed certificates for this host
        getCerts(tm, host, keystore, passArray);
        doc = getWsdl(loc, pass);

    }
    catch (IOException ioe) {

        invalidHostCert(passArray, keystore, tm, host);
    }

    Validate.notNull(doc, "No valid document format");
    return doc;
}
 
Example 20
Source File: CertificateUtil.java    From syndesis with Apache License 2.0 4 votes vote down vote up
public static TrustManager[] createTrustManagers(String brokerCertificate, String alias) throws GeneralSecurityException,
        IOException {
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("X509");
    trustManagerFactory.init(createKeyStore(brokerCertificate, alias));
    return trustManagerFactory.getTrustManagers();
}