List of usage examples for javax.net.ssl TrustManagerFactory getDefaultAlgorithm
public static final String getDefaultAlgorithm()
From source file:com.archivas.clienttools.arcutils.utils.net.GetCertsX509TrustManager.java
public void initPersistedTrustManager(boolean forcereload) throws NoSuchAlgorithmException, NoSuchProviderException, KeyStoreException { if (persistedTrustManager != null && !forcereload) { return;/*from ww w.jav a 2 s .c om*/ } String homedir = System.getProperty("user.home"); String fileNameTemplate = ConfigurationHelper.USER_CONFIG_DIRECTORY + ConfigurationHelper.getStringProperty("ssl.keystore.filename", "cacerts"); String fileName = MessageFormat.format(fileNameTemplate, homedir); persistedKeystoreFile = new File(fileName); try { persistedKeyStore = KeyStore.getInstance("JKS"); try { FileInputStream fis = null; if (persistedKeystoreFile.exists()) { fis = new FileInputStream(persistedKeystoreFile); } persistedKeyStore.load(fis, persistedKeystorePassword); } catch (FileNotFoundException e) { // Don't Care. Go on. LOG.log(Level.WARNING, "Unexpected Exception", e); } catch (IOException e) { LOG.log(Level.WARNING, "Unexpected Exception", e); } catch (CertificateException e) { LOG.log(Level.WARNING, "Unexpected Exception", e); } TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(persistedKeyStore); 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) { persistedTrustManager = (X509TrustManager) tms[i]; break; } } LOG.log(Level.FINER, "persistedTrustManager=" + persistedTrustManager); } catch (KeyStoreException e) { LOG.log(Level.WARNING, "Unexpected Exception", e); throw e; } catch (NoSuchAlgorithmException e) { LOG.log(Level.WARNING, "Unexpected Exception", e); throw e; } catch (RuntimeException e) { LOG.log(Level.WARNING, "Unexpected Exception", e); throw e; } }
From source file:com.thejoshwa.ultrasonic.androidapp.service.ssl.SSLSocketFactory.java
private static SSLContext createSSLContext(String algorithm, final KeyStore keystore, final String keystorePassword, final KeyStore truststore, final SecureRandom random, final TrustStrategy trustStrategy) throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, KeyManagementException { if (algorithm == null) { algorithm = TLS;/*from w w w . jav a 2 s. co m*/ } KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmfactory.init(keystore, keystorePassword != null ? keystorePassword.toCharArray() : null); KeyManager[] keymanagers = kmfactory.getKeyManagers(); TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmfactory.init(keystore); TrustManager[] trustmanagers = tmfactory.getTrustManagers(); if (trustmanagers != null && trustStrategy != null) { for (int i = 0; i < trustmanagers.length; i++) { TrustManager tm = trustmanagers[i]; if (tm instanceof X509TrustManager) { trustmanagers[i] = new TrustManagerDecorator((X509TrustManager) tm, trustStrategy); } } } SSLContext sslcontext = SSLContext.getInstance(algorithm); sslcontext.init(keymanagers, trustmanagers, random); return sslcontext; }
From source file:org.apache.synapse.transport.nhttp.config.ServerConnFactoryBuilder.java
protected SSLContextDetails createSSLContext(final OMElement keyStoreEl, final OMElement trustStoreEl, final OMElement cientAuthEl, final OMElement httpsProtocolsEl, final RevocationVerificationManager verificationManager, final String sslProtocol) throws AxisFault { KeyManager[] keymanagers = null; TrustManager[] trustManagers = null; if (keyStoreEl != null) { String location = getValueOfElementWithLocalName(keyStoreEl, "Location"); String type = getValueOfElementWithLocalName(keyStoreEl, "Type"); String storePassword = getValueOfElementWithLocalName(keyStoreEl, "Password"); String keyPassword = getValueOfElementWithLocalName(keyStoreEl, "KeyPassword"); FileInputStream fis = null; try {//w w w .j av a 2s . c o m KeyStore keyStore = KeyStore.getInstance(type); fis = new FileInputStream(location); if (log.isInfoEnabled()) { log.debug(name + " Loading Identity Keystore from : " + location); } keyStore.load(fis, storePassword.toCharArray()); KeyManagerFactory kmfactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmfactory.init(keyStore, keyPassword.toCharArray()); keymanagers = kmfactory.getKeyManagers(); if (log.isInfoEnabled() && keymanagers != null) { for (KeyManager keymanager : keymanagers) { if (keymanager instanceof X509KeyManager) { X509KeyManager x509keymanager = (X509KeyManager) keymanager; Enumeration<String> en = keyStore.aliases(); while (en.hasMoreElements()) { String s = en.nextElement(); X509Certificate[] certs = x509keymanager.getCertificateChain(s); if (certs == null) continue; for (X509Certificate cert : certs) { log.debug(name + " Subject DN: " + cert.getSubjectDN()); log.debug(name + " Issuer DN: " + cert.getIssuerDN()); } } } } } } catch (GeneralSecurityException gse) { log.error(name + " Error loading Key store : " + location, gse); throw new AxisFault("Error loading Key store : " + location, gse); } catch (IOException ioe) { log.error(name + " Error opening Key store : " + location, ioe); throw new AxisFault("Error opening Key store : " + location, ioe); } finally { if (fis != null) { try { fis.close(); } catch (IOException ignore) { } } } } if (trustStoreEl != null) { String location = getValueOfElementWithLocalName(trustStoreEl, "Location"); String type = getValueOfElementWithLocalName(trustStoreEl, "Type"); String storePassword = getValueOfElementWithLocalName(trustStoreEl, "Password"); FileInputStream fis = null; try { KeyStore trustStore = KeyStore.getInstance(type); fis = new FileInputStream(location); if (log.isInfoEnabled()) { log.debug(name + " Loading Trust Keystore from : " + location); } trustStore.load(fis, storePassword.toCharArray()); TrustManagerFactory trustManagerfactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerfactory.init(trustStore); trustManagers = trustManagerfactory.getTrustManagers(); } catch (GeneralSecurityException gse) { log.error(name + " Error loading Key store : " + location, gse); throw new AxisFault("Error loading Key store : " + location, gse); } catch (IOException ioe) { log.error(name + " Error opening Key store : " + location, ioe); throw new AxisFault("Error opening Key store : " + location, ioe); } finally { if (fis != null) { try { fis.close(); } catch (IOException ignore) { } } } } final String s = cientAuthEl != null ? cientAuthEl.getText() : null; final SSLClientAuth clientAuth; if ("optional".equalsIgnoreCase(s)) { clientAuth = SSLClientAuth.OPTIONAL; } else if ("require".equalsIgnoreCase(s)) { clientAuth = SSLClientAuth.REQUIRED; } else { clientAuth = null; } String[] httpsProtocols = null; final String configuredHttpsProtocols = httpsProtocolsEl != null ? httpsProtocolsEl.getText() : null; if (configuredHttpsProtocols != null && configuredHttpsProtocols.trim().length() != 0) { String[] configuredValues = configuredHttpsProtocols.trim().split(","); List<String> protocolList = new ArrayList<String>(configuredValues.length); for (String protocol : configuredValues) { if (!protocol.trim().isEmpty()) { protocolList.add(protocol.trim()); } } httpsProtocols = protocolList.toArray(new String[protocolList.size()]); } try { final String sslProtocolValue = sslProtocol != null ? sslProtocol : "TLS"; SSLContext sslContext = SSLContext.getInstance(sslProtocolValue); sslContext.init(keymanagers, trustManagers, null); ServerSSLSetupHandler sslSetupHandler = (clientAuth != null || httpsProtocols != null) ? new ServerSSLSetupHandler(clientAuth, httpsProtocols, verificationManager) : null; return new SSLContextDetails(sslContext, sslSetupHandler); } catch (GeneralSecurityException gse) { log.error(name + " 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:eu.eubrazilcc.lvl.core.http.client.TrustedHttpsClient.java
private static final void importCertificate(final String url, final KeyStore trustStore) throws Exception { final URL url2 = new URL(url); final SSLContext sslContext = SSLContext.getInstance("TLS"); final TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(trustStore); final X509TrustManager defaultTrustManager = (X509TrustManager) trustManagerFactory.getTrustManagers()[0]; final SavingTrustManager trustManager = new SavingTrustManager(defaultTrustManager); sslContext.init(null, new TrustManager[] { trustManager }, null); final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); final SSLSocket socket = (SSLSocket) sslSocketFactory.createSocket(url2.getHost(), url2.getPort() > 0 ? url2.getPort() : 443); socket.setSoTimeout(10000);// w w w . j av a2 s.com try { socket.startHandshake(); socket.close(); } catch (SSLException e) { } final X509Certificate[] chain = trustManager.chain; if (chain == null) { LOGGER.error("Could not obtain server certificate chain from: " + url); return; } final MessageDigest sha1 = MessageDigest.getInstance("SHA1"); final MessageDigest md5 = MessageDigest.getInstance("MD5"); for (int i = 0; i < chain.length; i++) { final X509Certificate cert = chain[i]; final String alias = url2.getHost() + "-" + (i + 1); if (!trustStore.containsAlias(alias)) { sha1.update(cert.getEncoded()); md5.update(cert.getEncoded()); LOGGER.trace("Importing certificate to trusted keystore >> " + "Subject: " + cert.getSubjectDN() + ", Issuer: " + cert.getIssuerDN() + ", SHA1: " + printHexBinary(sha1.digest()) + ", MD5: " + printHexBinary(md5.digest()) + ", Alias: " + alias); trustStore.setCertificateEntry(alias, cert); } } }
From source file:com.clustercontrol.plugin.impl.WebServicePlugin.java
/** * ???WebService?Agent????????//from www. j a v a 2s . c o m * @param addressPrefix ? http://x.x.x.x:xxxx? ? * @param addressBody ??? addressPrefix ?? * @param endpointInstance * @param threadPool ? */ protected void publish(String addressPrefix, String addressBody, Object endpointInstance, ThreadPoolExecutor threadPool) { try { final URL urlPrefix = new URL(addressPrefix); final String fulladdress = addressPrefix + addressBody; HttpsServer httpsServer = null; // ? HTTPS???????HttpsService???endpoit.publish????? // URL??????????HttpsService?????Hashmap???????HashMap? // HTTPSServer??????????? if ("https".equals(urlPrefix.getProtocol())) { httpsServer = httpsServerMap.get(addressPrefix); if (httpsServer == null) { // HTTPS Server??HTTPS????????????????????? String protocol = HinemosPropertyUtil.getHinemosPropertyStr("ws.https.protocol", "TLS"); String keystorePath = HinemosPropertyUtil.getHinemosPropertyStr("ws.https.keystore.path", HinemosPropertyDefault .getString(HinemosPropertyDefault.StringKey.WS_HTTPS_KEYSTORE_PATH)); String keystorePassword = HinemosPropertyUtil .getHinemosPropertyStr("ws.https.keystore.password", "hinemos"); String keystoreType = HinemosPropertyUtil.getHinemosPropertyStr("ws.https.keystore.type", "PKCS12"); log.info("Starting HTTPS Server..."); log.info("SSLContext: " + protocol + ", KeyStore: " + keystoreType); SSLContext ssl = SSLContext.getInstance(protocol); KeyManagerFactory keyFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); KeyStore store = KeyStore.getInstance(keystoreType); try (InputStream in = new FileInputStream(keystorePath)) { store.load(in, keystorePassword.toCharArray()); } keyFactory.init(store, keystorePassword.toCharArray()); TrustManagerFactory trustFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustFactory.init(store); ssl.init(keyFactory.getKeyManagers(), trustFactory.getTrustManagers(), new SecureRandom()); HttpsConfigurator configurator = new HttpsConfigurator(ssl); // ??HTTPSSever???Hashmap?? httpsServer = HttpsServer .create(new InetSocketAddress(urlPrefix.getHost(), urlPrefix.getPort()), 0); httpsServer.setHttpsConfigurator(configurator); httpsServerMap.put(addressPrefix, httpsServer); } } // ?????endpoint?? log.info("publish " + fulladdress); final Endpoint endpoint = Endpoint.create(endpointInstance); endpoint.setExecutor(threadPool); if (httpsServer != null) { endpoint.publish(httpsServer.createContext(addressBody)); } else { endpoint.publish(fulladdress); } endpointList.add(endpoint); } catch (NoSuchAlgorithmException | UnrecoverableKeyException | KeyStoreException | KeyManagementException | IOException | CertificateException | RuntimeException e) { log.warn("failed to publish : " + e.getClass().getSimpleName() + ", " + e.getMessage(), e); } finally { } }
From source file:org.elasticsearch.xpack.security.transport.ssl.SslIntegrationTests.java
public void testThatHttpUsingSSLv3IsRejected() throws Exception { SSLContext sslContext = SSLContext.getInstance("SSL"); TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); factory.init((KeyStore) null); sslContext.init(null, factory.getTrustManagers(), new SecureRandom()); SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslContext, new String[] { "SSLv3" }, null, NoopHostnameVerifier.INSTANCE); try (CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(sf).build()) { CloseableHttpResponse result = SocketAccess .doPrivileged(() -> client.execute(new HttpGet(getNodeUrl()))); fail("Expected a connection error due to SSLv3 not being supported by default"); } catch (Exception e) { assertThat(e, is(instanceOf(SSLHandshakeException.class))); }//from w w w . ja v a 2s . com }
From source file:com.adito.server.jetty.CustomJsseListener.java
protected SSLServerSocketFactory createFactory() throws Exception { if (KeyStoreManager.getInstance(KeyStoreManager.DEFAULT_KEY_STORE).isKeyStoreEmpty()) { throw new Exception( "The keystore does not contain any certificates. Please run the installation wizard (--install)."); }//w w w .ja va 2 s .co m KeyStore ks = KeyStoreManager.getInstance(KeyStoreManager.DEFAULT_KEY_STORE).getKeyStore(); String pw = ContextHolder.getContext().getConfig() .retrieveProperty(new ContextKey("webServer.keystore.sslCertificate.password")); KeyManager[] kma = new KeyManager[] { new CustomKeyManager(pw) }; TrustManager[] tma = null; if (trustManager == null) { TrustManagerFactory tm = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tm.init(ks); tma = tm.getTrustManagers(); } else { // LDP - Add the existing trust managers so that outgoing certificates are still trusted. TrustManagerFactory tm = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tm.init(ks); tma = new TrustManager[tm.getTrustManagers().length + 1]; for (int i = 0; i < tm.getTrustManagers().length; i++) { tma[i] = tm.getTrustManagers()[i]; } tma[tma.length - 1] = trustManager; } SSLContext sslc = SSLContext.getInstance("SSL"); sslc.init(kma, tma, SecureRandom.getInstance("SHA1PRNG")); SSLServerSocketFactory ssfc = sslc.getServerSocketFactory(); if (log.isInfoEnabled()) log.info("SSLServerSocketFactory=" + ssfc); initialised = true; return ssfc; }
From source file:com.sslexplorer.server.jetty.CustomJsseListener.java
protected SSLServerSocketFactory createFactory() throws Exception { if (KeyStoreManager.getInstance(KeyStoreManager.DEFAULT_KEY_STORE).isKeyStoreEmpty()) { throw new Exception( "The keystore does not contain any certificates. Please run the installation wizard (--install)."); }//from w ww . j a v a 2 s. co m KeyStore ks = KeyStoreManager.getInstance(KeyStoreManager.DEFAULT_KEY_STORE).getKeyStore(); String pw = ContextHolder.getContext().getConfig() .retrieveProperty(new ContextKey("webServer.keystore.sslCertificate.password")); KeyManager[] kma = new KeyManager[] { new CustomKeyManager(pw) }; TrustManager[] tma = null; if (trustManager == null) { TrustManagerFactory tm = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tm.init(ks); tma = tm.getTrustManagers(); } else { // LDP - Add the existing trust managers so that outgoing certificates are still trusted. TrustManagerFactory tm = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tm.init(ks); tma = new TrustManager[tm.getTrustManagers().length + 1]; for (int i = 0; i < tm.getTrustManagers().length - 1; i++) { tma[i] = tm.getTrustManagers()[i]; } tma[tma.length - 1] = trustManager; } SSLContext sslc = SSLContext.getInstance("SSL"); sslc.init(kma, tma, SecureRandom.getInstance("SHA1PRNG")); SSLServerSocketFactory ssfc = sslc.getServerSocketFactory(); if (log.isInfoEnabled()) log.info("SSLServerSocketFactory=" + ssfc); initialised = true; return ssfc; }