List of usage examples for javax.net.ssl TrustManagerFactory getTrustManagers
public final TrustManager[] getTrustManagers()
From source file:org.nectarframework.base.service.nanohttp.NanoHttpService.java
/** * Creates an SSLSocketFactory for HTTPS. Pass a KeyStore resource with your * certificate and passphrase//w ww . ja v a 2 s . c o m */ public ServerSocket makeSSLServerSocket(String keyAndTrustStoreClasspathPath, char[] passphrase) throws IOException { try { KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); InputStream keystoreStream = new FileInputStream(new File(keyAndTrustStoreClasspathPath)); keystore.load(keystoreStream, passphrase); KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keystore, passphrase); SSLServerSocketFactory res = null; try { TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keystore); SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null); res = ctx.getServerSocketFactory(); } catch (Exception e) { throw new IOException(e.getMessage()); } SSLServerSocket ss = null; ss = (SSLServerSocket) res.createServerSocket(); ss.setEnabledProtocols(ss.getSupportedProtocols()); ss.setUseClientMode(false); ss.setWantClientAuth(false); ss.setNeedClientAuth(false); return ss; } catch (Exception e) { throw new IOException(e.getMessage()); } }
From source file:org.mitre.svmp.net.SSLConfig.java
@SuppressLint("TrulyRandom") private void doConfigure() throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException, KeyManagementException { // find out if we should use the MemorizingTrustManager instead of the system trust store (set in Preferences) boolean useMTM = Utility.getPrefBool(context, R.string.preferenceKey_connection_useMTM, R.string.preferenceValue_connection_useMTM); // determine whether we should use client certificate authentication boolean useCertificateAuth = Constants.API_14 && (connectionInfo.getAuthType() & CertificateModule.AUTH_MODULE_ID) == CertificateModule.AUTH_MODULE_ID; // set up key managers KeyManager[] keyManagers = null; // if certificate authentication is enabled, use a key manager with the provided alias if (useCertificateAuth) { keyManagers = new KeyManager[] { new SVMPKeyManager(context, connectionInfo.getCertificateAlias()) }; }// w ww . ja v a 2s .c o m // set up trust managers TrustManager[] trustManagers = null; KeyStore localTrustStore = KeyStore.getInstance("BKS"); InputStream in = context.getResources().openRawResource(R.raw.client_truststore); localTrustStore.load(in, Constants.TRUSTSTORE_PASSWORD.toCharArray()); TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(localTrustStore); // 1) If "res/raw/client_truststore.bks" is not empty, use it as the pinned cert trust store (default is empty) // 2) Otherwise, if the "Show certificate dialog" developer preference is enabled, use that (default is disabled) // 3) Otherwise, use the default system trust store, consists of normal trusted Android CA certs if (localTrustStore.size() > 0) { // this means that "res/raw/client_truststore.bks" has been replaced with a trust store that is not empty // we will use that "pinned" store to check server certificate trust Log.d(TAG, "SSLConfig: Using static BKS trust store to check server cert trust"); trustManagers = trustManagerFactory.getTrustManagers(); // After switching to WebSockets, MTM causes the app to freeze; removed for now } else if (useMTM) { // by default useMTM is false ("Show certificate dialog" in developer preferences) // this creates a certificate dialog to decide what to do with untrusted certificates, instead of flat-out rejecting them Log.d(TAG, "SSLConfig: Static BKS trust store is empty but MTM is enabled, using MTM to check server cert trust"); mtm = new MemorizingTrustManager(context); mtm.bindDisplayActivity(activity); trustManagers = new X509TrustManager[] { mtm }; } else { Log.d(TAG, "SSLConfig: Static BKS trust store is empty and MTM is disabled, using system trust store to check server cert trust"); // leaving trustManagers null accomplishes this } PRNGFixes.apply(); // fix Android SecureRandom issue on pre-KitKat platforms sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyManagers, trustManagers, new SecureRandom()); }
From source file:ddf.security.realm.sts.StsRealm.java
/** * Setup trust store for SSL client./*from w w w . j av a 2s . c om*/ */ private void setupTrustStore(TLSClientParameters tlsParams, String trustStorePath, String trustStorePassword) { File trustStoreFile = new File(trustStorePath); if (trustStoreFile.exists() && trustStorePassword != null) { KeyStore trustStore = null; FileInputStream fis = null; try { trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); fis = new FileInputStream(trustStoreFile); LOGGER.debug("Loading trustStore"); trustStore.load(fis, trustStorePassword.toCharArray()); TrustManagerFactory trustFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustFactory.init(trustStore); LOGGER.debug("trust manager factory initialized"); TrustManager[] tm = trustFactory.getTrustManagers(); tlsParams.setTrustManagers(tm); } catch (FileNotFoundException e) { LOGGER.error("Unable to find SSL store: " + trustStorePath, e); } catch (IOException e) { LOGGER.error("Unable to load trust store. " + trustStore, e); } catch (CertificateException e) { LOGGER.error("Unable to load certificates from trust store. " + trustStore, e); } catch (KeyStoreException e) { LOGGER.error("Unable to read trust store: ", e); } catch (NoSuchAlgorithmException e) { LOGGER.error("Problems creating SSL socket. Usually this is " + "referring to the certificate sent by the server not being trusted by the client.", e); } finally { IOUtils.closeQuietly(fis); } } }
From source file:com.photon.phresco.framework.rest.api.util.FrameworkServiceUtil.java
public static List<CertificateInfo> getCertificate(String host, int port) throws PhrescoException { List<CertificateInfo> certificates = new ArrayList<CertificateInfo>(); CertificateInfo info;/*from www . j av a 2 s . c o m*/ try { KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); SSLContext context = SSLContext.getInstance("TLS"); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0]; SavingTrustManager tm = new SavingTrustManager(defaultTrustManager); context.init(null, new TrustManager[] { tm }, null); SSLSocketFactory factory = context.getSocketFactory(); SSLSocket socket = (SSLSocket) factory.createSocket(host, port); socket.setSoTimeout(10000); try { socket.startHandshake(); socket.close(); } catch (SSLException e) { } X509Certificate[] chain = tm.chain; for (int i = 0; i < chain.length; i++) { X509Certificate x509Certificate = chain[i]; String subjectDN = x509Certificate.getSubjectDN().getName(); String[] split = subjectDN.split(","); info = new CertificateInfo(); info.setSubjectDN(subjectDN); info.setDisplayName(split[0]); info.setCertificate(x509Certificate); certificates.add(info); } } catch (Exception e) { throw new PhrescoException(e); } return certificates; }
From source file:org.gvnix.service.roo.addon.addon.security.SecurityServiceImpl.java
/** * Get certificates in the chain of the host server and import them. * <p>/*from www . j a v a2 s. co m*/ * 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; }
From source file:com.ibm.iotf.client.AbstractClient.java
static SSLSocketFactory getSocketFactory(final String caCrtFile, final String crtFile, final String keyFile, final String password) throws IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException, KeyManagementException { Security.addProvider(new BouncyCastleProvider()); X509Certificate caCert = null; if (caCrtFile != null) { // load CA certificate PEMReader reader = new PEMReader( new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(caCrtFile))))); caCert = (X509Certificate) reader.readObject(); reader.close();//from ww w. ja v a 2 s . co m } else { ClassLoader classLoader = AbstractClient.class.getClassLoader(); PEMReader reader = new PEMReader( new InputStreamReader(classLoader.getResource(SERVER_MESSAGING_PEM).openStream())); caCert = (X509Certificate) reader.readObject(); reader.close(); } PEMReader reader = new PEMReader( new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(crtFile))))); X509Certificate cert = (X509Certificate) reader.readObject(); reader.close(); // load client private key reader = new PEMReader( new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(keyFile))))); KeyPair key = (KeyPair) reader.readObject(); reader.close(); TrustManagerFactory tmf = null; if (caCert != null) { // CA certificate is used to authenticate server KeyStore caKs = KeyStore.getInstance("JKS"); //caKs.load(null, null); caKs.load(null, null); caKs.setCertificateEntry("ca-certificate", caCert); tmf = TrustManagerFactory.getInstance("PKIX"); tmf.init(caKs); } // client key and certificates are sent to server so it can authenticate us KeyStore ks = KeyStore.getInstance("JKS"); ks.load(null, null); ks.setCertificateEntry("certificate", cert); ks.setKeyEntry("private-key", key.getPrivate(), password.toCharArray(), new java.security.cert.Certificate[] { cert }); KeyManagerFactory kmf = KeyManagerFactory.getInstance("PKIX"); kmf.init(ks, password.toCharArray()); // finally, create SSL socket factory SSLContext context = SSLContext.getInstance("TLSv1.2"); if (tmf != null) { context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); } else { context.init(kmf.getKeyManagers(), null, null); } return context.getSocketFactory(); }
From source file:com.predic8.membrane.core.transport.ssl.SSLContext.java
public SSLContext(SSLParser sslParser, ResolverMap resourceResolver, String baseLocation) { this.sslParser = sslParser; try {//from ww w . ja va2 s .c o m String algorihm = KeyManagerFactory.getDefaultAlgorithm(); if (sslParser.getAlgorithm() != null) algorihm = sslParser.getAlgorithm(); KeyManagerFactory kmf = null; String keyStoreType = "JKS"; if (sslParser.getKeyStore() != null) { if (sslParser.getKeyStore().getKeyAlias() != null) throw new InvalidParameterException("keyAlias is not yet supported."); char[] keyPass = "changeit".toCharArray(); if (sslParser.getKeyStore().getKeyPassword() != null) keyPass = sslParser.getKeyStore().getKeyPassword().toCharArray(); if (sslParser.getKeyStore().getType() != null) keyStoreType = sslParser.getKeyStore().getType(); KeyStore ks = openKeyStore(sslParser.getKeyStore(), "JKS", keyPass, resourceResolver, baseLocation); kmf = KeyManagerFactory.getInstance(algorihm); kmf.init(ks, keyPass); Enumeration<String> aliases = ks.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); if (ks.isKeyEntry(alias)) { // first key is used by the KeyManagerFactory Certificate c = ks.getCertificate(alias); if (c instanceof X509Certificate) { X509Certificate x = (X509Certificate) c; dnsNames = new ArrayList<String>(); Collection<List<?>> subjectAlternativeNames = x.getSubjectAlternativeNames(); if (subjectAlternativeNames != null) for (List<?> l : subjectAlternativeNames) { if (l.get(0) instanceof Integer && ((Integer) l.get(0) == 2)) dnsNames.add(l.get(1).toString()); } } break; } } } TrustManagerFactory tmf = null; if (sslParser.getTrustStore() != null) { String trustAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); if (sslParser.getTrustStore().getAlgorithm() != null) trustAlgorithm = sslParser.getTrustStore().getAlgorithm(); KeyStore ks = openKeyStore(sslParser.getTrustStore(), keyStoreType, null, resourceResolver, baseLocation); tmf = TrustManagerFactory.getInstance(trustAlgorithm); tmf.init(ks); } TrustManager[] tms = tmf != null ? tmf.getTrustManagers() : null /* trust anyone: new TrustManager[] { new NullTrustManager() } */; if (sslParser.isIgnoreTimestampCheckFailure()) tms = new TrustManager[] { new TrustManagerWrapper(tms, true) }; if (sslParser.getProtocol() != null) sslc = javax.net.ssl.SSLContext.getInstance(sslParser.getProtocol()); else sslc = javax.net.ssl.SSLContext.getInstance("TLS"); sslc.init(kmf != null ? kmf.getKeyManagers() : null, tms, null); if (sslParser.getCiphers() != null) { ciphers = sslParser.getCiphers().split(","); Set<String> supportedCiphers = Sets.newHashSet(sslc.getSocketFactory().getSupportedCipherSuites()); for (String cipher : ciphers) { if (!supportedCiphers.contains(cipher)) throw new InvalidParameterException("Unknown cipher " + cipher); if (cipher.contains("_RC4_")) log.warn("Cipher " + cipher + " uses RC4, which is deprecated."); } } else { // use all default ciphers except those using RC4 String supportedCiphers[] = sslc.getSocketFactory().getDefaultCipherSuites(); ArrayList<String> ciphers = new ArrayList<String>(supportedCiphers.length); for (String cipher : supportedCiphers) if (!cipher.contains("_RC4_")) ciphers.add(cipher); sortCiphers(ciphers); this.ciphers = ciphers.toArray(new String[ciphers.size()]); } if (setUseCipherSuitesOrderMethod == null) log.warn( "Cannot set the cipher suite order before Java 8. This prevents Forward Secrecy with some SSL clients."); if (sslParser.getProtocols() != null) { protocols = sslParser.getProtocols().split(","); } else { protocols = null; } if (sslParser.getClientAuth() == null) { needClientAuth = false; wantClientAuth = false; } else if (sslParser.getClientAuth().equals("need")) { needClientAuth = true; wantClientAuth = true; } else if (sslParser.getClientAuth().equals("want")) { needClientAuth = false; wantClientAuth = true; } else { throw new RuntimeException("Invalid value '" + sslParser.getClientAuth() + "' in clientAuth: expected 'want', 'need' or not set."); } } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.deviceconnect.android.message.DevicePluginContext.java
/** * SSLContext ?????.//from w ww. j ava2s. c om * <p> * ? Web ?????Manager???????????SSLContext ??? * </p> * @param keyStore * @return SSLContext? * @throws GeneralSecurityException SSLContext??????? */ protected SSLContext createSSLContext(final KeyStore keyStore) throws GeneralSecurityException { SSLContext sslContext = SSLContext.getInstance("TLS"); KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keyStore, "0000".toCharArray()); TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keyStore); sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom()); return sslContext; }
From source file:com.cisco.oss.foundation.http.apache.ApacheHttpClient.java
@Override protected void configureClient() { RequestConfig.Builder requestBuilder = RequestConfig.custom(); requestBuilder = requestBuilder.setConnectTimeout(metadata.getConnectTimeout()); requestBuilder = requestBuilder.setSocketTimeout(metadata.getReadTimeout()); requestBuilder = requestBuilder.setStaleConnectionCheckEnabled(metadata.isStaleConnectionCheckEnabled()); RequestConfig requestConfig = requestBuilder.build(); boolean addSslSupport = StringUtils.isNotEmpty(metadata.getKeyStorePath()) && StringUtils.isNotEmpty(metadata.getKeyStorePassword()); boolean addTrustSupport = StringUtils.isNotEmpty(metadata.getTrustStorePath()) && StringUtils.isNotEmpty(metadata.getTrustStorePassword()); autoCloseable = metadata.isAutoCloseable(); HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); SSLContext sslContext = null; try {//from www . java 2s. c o m String keystoreType = "JKS"; if (addSslSupport && addTrustSupport) { KeyStore keyStore = KeyStore.getInstance(keystoreType); keyStore.load(new FileInputStream(metadata.getKeyStorePath()), metadata.getKeyStorePassword().toCharArray()); KeyStore trustStore = KeyStore.getInstance(keystoreType); trustStore.load(new FileInputStream(metadata.getTrustStorePath()), metadata.getTrustStorePassword().toCharArray()); sslContext = SSLContexts.custom().useProtocol("TLS") .loadKeyMaterial(keyStore, metadata.getKeyStorePassword().toCharArray()) .loadTrustMaterial(trustStore, null).build(); } else if (addSslSupport) { TrustManagerFactory tmf = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); KeyStore keyStore = KeyStore.getInstance(keystoreType); keyStore.load(new FileInputStream(metadata.getKeyStorePath()), metadata.getKeyStorePassword().toCharArray()); tmf.init(keyStore); sslContext = SSLContexts.custom().useProtocol("SSL") .loadKeyMaterial(keyStore, metadata.getKeyStorePassword().toCharArray()).build(); sslContext.init(null, tmf.getTrustManagers(), null); SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier); httpClientBuilder.setSSLSocketFactory(sf); } else if (addTrustSupport) { KeyStore trustStore = KeyStore.getInstance(keystoreType); trustStore.load(new FileInputStream(metadata.getTrustStorePath()), metadata.getTrustStorePassword().toCharArray()); sslContext = SSLContexts.custom().useProtocol("TLS").loadTrustMaterial(trustStore, null).build(); } if (addSslSupport | addTrustSupport) { SSLContext.setDefault(sslContext); httpClientBuilder.setSslcontext(sslContext); } } catch (Exception e) { LOGGER.error("can't set TLS Support. Error is: {}", e, e); } httpClientBuilder.setMaxConnPerRoute(metadata.getMaxConnectionsPerAddress()) .setMaxConnTotal(metadata.getMaxConnectionsTotal()).setDefaultRequestConfig(requestConfig) .evictExpiredConnections().evictIdleConnections(metadata.getIdleTimeout(), TimeUnit.MILLISECONDS) .setKeepAliveStrategy(new InfraConnectionKeepAliveStrategy(metadata.getIdleTimeout())); HttpAsyncClientBuilder httpAsyncClientBuilder = HttpAsyncClients.custom(); httpAsyncClientBuilder.setDefaultRequestConfig(requestConfig) .setMaxConnPerRoute(metadata.getMaxConnectionsPerAddress()) .setMaxConnTotal(metadata.getMaxConnectionsTotal()) .setKeepAliveStrategy(new InfraConnectionKeepAliveStrategy(metadata.getIdleTimeout())) .setSSLContext(sslContext); if (metadata.isDisableCookies()) { httpClientBuilder.disableCookieManagement(); httpAsyncClientBuilder.disableCookieManagement(); } if (hostnameVerifier != null) { httpClientBuilder.setSSLHostnameVerifier(hostnameVerifier); httpAsyncClientBuilder.setSSLHostnameVerifier(hostnameVerifier); } if (!followRedirects) { httpClientBuilder.disableRedirectHandling(); } httpClient = httpClientBuilder.build(); httpAsyncClient = httpAsyncClientBuilder.build(); httpAsyncClient.start(); }