List of usage examples for javax.net.ssl TrustManagerFactory getDefaultAlgorithm
public static final String getDefaultAlgorithm()
From source file:org.disrupted.rumble.database.statistics.StatisticManager.java
public void onEventAsync(LinkLayerStarted event) { if (!event.linkLayerIdentifier.equals(WifiLinkLayerAdapter.LinkLayerIdentifier)) return;/*w w w.j a v a 2 s .c o m*/ if (RumblePreferences.UserOkWithSharingAnonymousData(RumbleApplication.getContext()) && RumblePreferences.isTimeToSync(RumbleApplication.getContext())) { if (!NetUtil.isURLReachable("http://disruptedsystems.org/")) return; try { // generate the JSON file byte[] json = generateStatJSON().toString().getBytes(); // configure SSL CertificateFactory cf = CertificateFactory.getInstance("X.509"); InputStream caInput = new BufferedInputStream( RumbleApplication.getContext().getAssets().open("certs/disruptedsystemsCA.pem")); Certificate ca = cf.generateCertificate(caInput); String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("ca", ca); String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, tmf.getTrustManagers(), null); URL url = new URL("https://data.disruptedsystems.org/post"); HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection(); urlConnection.setSSLSocketFactory(sslContext.getSocketFactory()); // then configure the header urlConnection.setInstanceFollowRedirects(true); urlConnection.setRequestMethod("POST"); urlConnection.setDoOutput(true); urlConnection.setRequestProperty("Content-Type", "application/json"); urlConnection.setRequestProperty("Accept", "application/json"); urlConnection.setRequestProperty("charset", "utf-8"); urlConnection.setRequestProperty("Content-Length", Integer.toString(json.length)); urlConnection.setUseCaches(false); // connect and send the JSON urlConnection.setConnectTimeout(10 * 1000); urlConnection.connect(); urlConnection.getOutputStream().write(json); if (urlConnection.getResponseCode() != 200) throw new IOException("request failed"); // erase the database RumblePreferences.updateLastSync(RumbleApplication.getContext()); cleanDatabase(); } catch (Exception ex) { Log.e(TAG, "Failed to establish SSL connection to server: " + ex.toString()); } } }
From source file:org.apache.hadoop.gateway.jetty.JettyHttpsTest.java
private static TrustManager[] createTrustManagers(String trustStoreType, String trustStorePath, String trustStorePassword) throws Exception { KeyStore trustStore = loadKeyStore(trustStoreType, trustStorePath, trustStorePassword); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(trustStore);//from ww w .jav a 2 s .c o m return tmf.getTrustManagers(); }
From source file:org.springframework.cloud.vault.ClientHttpRequestFactoryFactory.java
private static TrustManagerFactory createTrustManagerFactory(Resource trustFile, String storePassword) throws GeneralSecurityException, IOException { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); try (InputStream inputStream = trustFile.getInputStream()) { trustStore.load(inputStream, StringUtils.hasText(storePassword) ? storePassword.toCharArray() : null); }/*from w w w. ja va2 s. c o m*/ TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(trustStore); return trustManagerFactory; }
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()) }; }/*from ww w . jav a2 s.co 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.catalog.source.opensearch.SecureRemoteConnectionImpl.java
/** * Creates a new SSLSocketFactory from a truststore and keystore. This is used during SSL * communications with the server./*from www .jav a 2 s .co m*/ * * @param trustStoreLoc * File path to the truststore. * @param trustStorePass * Password to the truststore. * @param keyStoreLoc * File path to the keystore. * @param keyStorePass * Password to the keystore. * @return new SSLSocketFactory instance containing the trust and key stores. * @throws KeyStoreException * @throws IOException * @throws CertificateException * @throws NoSuchAlgorithmException * @throws UnrecoverableKeyException * @throws KeyManagementException */ public SSLSocketFactory createSocket(String trustStoreLoc, String trustStorePass, String keyStoreLoc, String keyStorePass) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException, KeyManagementException { String methodName = "createSocket"; LOGGER.debug("ENTERING: " + methodName); LOGGER.debug("trustStoreLoc = " + trustStoreLoc); FileInputStream trustFIS = new FileInputStream(trustStoreLoc); LOGGER.debug("keyStoreLoc = " + keyStoreLoc); FileInputStream keyFIS = new FileInputStream(keyStoreLoc); // truststore stuff KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); try { LOGGER.debug("Loading trustStore"); trustStore.load(trustFIS, trustStorePass.toCharArray()); } finally { IOUtils.closeQuietly(trustFIS); } TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(trustStore); LOGGER.debug("trust manager factory initialized"); // keystore stuff KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); try { LOGGER.debug("Loading keyStore"); keyStore.load(keyFIS, keyStorePass.toCharArray()); } finally { IOUtils.closeQuietly(keyFIS); } KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(keyStore, keyStorePass.toCharArray()); LOGGER.debug("key manager factory initialized"); // ssl context SSLContext sslCtx = SSLContext.getInstance("TLS"); sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); LOGGER.debug("EXITING: " + methodName); return sslCtx.getSocketFactory(); }
From source file:ddf.security.settings.impl.SecuritySettingsServiceImpl.java
@Override public TLSClientParameters getTLSParameters() { TLSClientParameters tlsParams = new TLSClientParameters(); try {//from w w w.j a v a2 s . c om TrustManagerFactory trustFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustFactory.init(trustStore); TrustManager[] tm = trustFactory.getTrustManagers(); tlsParams.setTrustManagers(tm); KeyManagerFactory keyFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyFactory.init(keyStore, keystorePassword.toCharArray()); KeyManager[] km = keyFactory.getKeyManagers(); tlsParams.setKeyManagers(km); } catch (NoSuchAlgorithmException | KeyStoreException | UnrecoverableKeyException e) { LOGGER.warn( "Could not fully load keystore/truststore into TLSParameters. Parameters may not be fully functional.", e); } FiltersType filter = new FiltersType(); filter.getInclude().addAll(SSL_ALLOWED_ALGORITHMS); filter.getExclude().addAll(SSL_DISALLOWED_ALGORITHMS); tlsParams.setCipherSuitesFilter(filter); return tlsParams; }
From source file:com.mgmtp.perfload.core.client.web.ssl.LtSSLSocketFactory.java
private TrustManager[] createTrustManagers(final KeyStore keyStore) throws KeyStoreException, NoSuchAlgorithmException { log.debug("Initializing trust managers"); TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmfactory.init(keyStore);/*from ww w . jav a 2 s .co m*/ TrustManager[] trustmanagers = tmfactory.getTrustManagers(); for (int i = 0; i < trustmanagers.length; ++i) { if (trustmanagers[i] instanceof X509TrustManager) { trustmanagers[i] = new LtX509TrustManager((X509TrustManager) trustmanagers[i]); } } return trustmanagers; }
From source file:org.apache.axis2.transport.nhttp.HttpCoreNIOSSLSender.java
protected SSLContext getSSLContext(TransportOutDescription transportOut) throws AxisFault { KeyManager[] keymanagers = null; TrustManager[] trustManagers = null; Parameter keyParam = transportOut.getParameter("keystore"); Parameter trustParam = transportOut.getParameter("truststore"); if (keyParam != null) { OMElement ksEle = keyParam.getParameterElement().getFirstElement(); String location = ksEle.getFirstChildWithName(new QName("Location")).getText(); String type = ksEle.getFirstChildWithName(new QName("Type")).getText(); String storePassword = ksEle.getFirstChildWithName(new QName("Password")).getText(); String keyPassword = ksEle.getFirstChildWithName(new QName("KeyPassword")).getText(); try {//from ww w. j a v a 2 s . c o m KeyStore keyStore = KeyStore.getInstance(type); URL url = getClass().getClassLoader().getResource(location); log.debug("Loading Key Store from URL : " + url); keyStore.load(url.openStream(), storePassword.toCharArray()); KeyManagerFactory kmfactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmfactory.init(keyStore, keyPassword.toCharArray()); keymanagers = kmfactory.getKeyManagers(); } catch (GeneralSecurityException gse) { log.error("Error loading Key store : " + location, gse); throw new AxisFault("Error loading Key store : " + location, gse); } catch (IOException ioe) { log.error("Error opening Key store : " + location, ioe); throw new AxisFault("Error opening Key store : " + location, ioe); } } if (trustParam != null) { OMElement tsEle = trustParam.getParameterElement().getFirstElement(); String location = tsEle.getFirstChildWithName(new QName("Location")).getText(); String type = tsEle.getFirstChildWithName(new QName("Type")).getText(); String storePassword = tsEle.getFirstChildWithName(new QName("Password")).getText(); try { KeyStore trustStore = KeyStore.getInstance(type); URL url = getClass().getClassLoader().getResource(location); log.debug("Loading Trust Key Store from URL : " + url); trustStore.load(url.openStream(), storePassword.toCharArray()); TrustManagerFactory trustManagerfactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerfactory.init(trustStore); trustManagers = trustManagerfactory.getTrustManagers(); } catch (GeneralSecurityException gse) { log.error("Error loading Key store : " + location, gse); throw new AxisFault("Error loading Key store : " + location, gse); } catch (IOException ioe) { log.error("Error opening Key store : " + location, ioe); throw new AxisFault("Error opening Key store : " + location, ioe); } } try { SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(keymanagers, trustManagers, null); return sslcontext; } catch (GeneralSecurityException gse) { log.error("Unable to create SSL context with the given configuration", gse); throw new AxisFault("Unable to create SSL context with the given configuration", gse); } }
From source file:com.gsf.dowload.nfe.HSProtocolSocketFactory.java
public TrustManager[] createTrustManagers() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException { KeyStore trustStore = KeyStore.getInstance("JKS"); trustStore.load(new FileInputStream(TRUSTSTORE), "sistec".toCharArray()); TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(trustStore); return trustManagerFactory.getTrustManagers(); }
From source file:com.amazon.speech.speechlet.authentication.SpeechletRequestSignatureVerifier.java
/** * Retrieves the certificate from the specified URL and confirms that the certificate is valid. * * @param signingCertificateChainUrl/*from ww w .j ava2s . c o m*/ * the URL to retrieve the certificate chain from * @return the certificate at the specified URL, if the certificate is valid * @throws CertificateException * if the certificate cannot be retrieve or is invalid */ public static X509Certificate retrieveAndVerifyCertificateChain(final String signingCertificateChainUrl) throws CertificateException { try (InputStream in = getAndVerifySigningCertificateChainUrl(signingCertificateChainUrl).openStream()) { CertificateFactory certificateFactory = CertificateFactory.getInstance(Sdk.SIGNATURE_CERTIFICATE_TYPE); @SuppressWarnings("unchecked") Collection<X509Certificate> certificateChain = (Collection<X509Certificate>) certificateFactory .generateCertificates(in); /* * check the before/after dates on the certificate date to confirm that it is valid on * the current date */ X509Certificate signingCertificate = certificateChain.iterator().next(); signingCertificate.checkValidity(); // check the certificate chain TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init((KeyStore) null); X509TrustManager x509TrustManager = null; for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) { if (trustManager instanceof X509TrustManager) { x509TrustManager = (X509TrustManager) trustManager; } } if (x509TrustManager == null) { throw new IllegalStateException( "No X509 TrustManager available. Unable to check certificate chain"); } else { x509TrustManager.checkServerTrusted( certificateChain.toArray(new X509Certificate[certificateChain.size()]), Sdk.SIGNATURE_KEY_TYPE); } /* * verify Echo API's hostname is specified as one of subject alternative names on the * signing certificate */ if (!subjectAlernativeNameListContainsEchoSdkDomainName( signingCertificate.getSubjectAlternativeNames())) { throw new CertificateException("The provided certificate is not valid for the Echo SDK"); } return signingCertificate; } catch (KeyStoreException | IOException | NoSuchAlgorithmException ex) { throw new CertificateException("Unable to verify certificate at URL: " + signingCertificateChainUrl, ex); } }