List of usage examples for java.security KeyStore getInstance
public static KeyStore getInstance(String type) throws KeyStoreException
From source file:org.apache.hadoop.gateway.jetty.JettyHttpsTest.java
private static KeyStore loadKeyStore(String type, String path, String password) throws IOException, NoSuchAlgorithmException, CertificateException, KeyStoreException { KeyStore keyStore = KeyStore.getInstance(type); InputStream keystoreInput = new FileInputStream(path); keyStore.load(keystoreInput, password.toCharArray()); return keyStore; }
From source file:com.smoketurner.dropwizard.riak.config.RiakConfiguration.java
@JsonIgnore public RiakClient build(@Nonnull final Environment environment) throws UnknownHostException, KeyStoreException { Objects.requireNonNull(environment); final RiakNode.Builder builder = new RiakNode.Builder().withMinConnections(minConnections) .withMaxConnections(maxConnections) .withConnectionTimeout(Ints.checkedCast(connectionTimeout.toMilliseconds())) .withIdleTimeout(Ints.checkedCast(idleTimeout.toMilliseconds())) .withBlockOnMaxConnections(blockOnMaxConnections); if (!Strings.isNullOrEmpty(username) && !Strings.isNullOrEmpty(password) && !Strings.isNullOrEmpty(keyStore)) { // TODO finish keyStore implementation final KeyStore keystore = KeyStore.getInstance("PKS"); builder.withAuth(username, password, keystore); }//from w ww .j a va 2 s . c o m final List<RiakNode> nodes = new ArrayList<>(); for (HostAndPort address : this.nodes) { final RiakNode node = builder.withRemoteAddress(address.getHostText()) .withRemotePort(address.getPortOrDefault(RiakNode.Builder.DEFAULT_REMOTE_PORT)).build(); nodes.add(node); } DefaultCharset.set(StandardCharsets.UTF_8); final RiakCluster cluster = RiakCluster.builder(nodes).withExecutionAttempts(executionAttempts).build(); environment.lifecycle().manage(new RiakClusterManager(cluster)); final RiakClient client = new RiakClient(cluster); environment.healthChecks().register("riak", new RiakHealthCheck(client)); return client; }
From source file:io.wcm.caravan.commons.httpclient.impl.helpers.CertificateLoader.java
/** * Build TrustManagerFactory./*www . jav a 2 s .com*/ * @param trustStoreStream Truststore input stream * @param storeProperties store properties * @return TrustManagerFactory * @throws IOException * @throws GeneralSecurityException */ private static TrustManagerFactory getTrustManagerFactory(InputStream trustStoreStream, StoreProperties storeProperties) throws IOException, GeneralSecurityException { KeyStore jks = KeyStore.getInstance(storeProperties.getType()); jks.load(trustStoreStream, storeProperties.getPassword().toCharArray()); TrustManagerFactory tmf = TrustManagerFactory.getInstance(storeProperties.getManagerType()); tmf.init(jks); return tmf; }
From source file:org.gameontext.map.auth.PlayerClient.java
/** * Obtain the key we'll use to sign the jwts we use to talk to Player endpoints. * * @throws IOException//ww w .j av a 2 s . com * if there are any issues with the keystore processing. */ private synchronized void getKeyStoreInfo() { try { // load up the keystore.. FileInputStream is = new FileInputStream(keyStore); KeyStore signingKeystore = KeyStore.getInstance(KeyStore.getDefaultType()); signingKeystore.load(is, keyStorePW.toCharArray()); // grab the key we'll use to sign signingKey = signingKeystore.getKey(keyStoreAlias, keyStorePW.toCharArray()); } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | UnrecoverableKeyException | IOException e) { throw new IllegalStateException("Unable to get required keystore: " + keyStore, e); } }
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 ww w . j a v a 2 s .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(); }
From source file:com.aware.ui.Plugins_Manager.java
/** * Downloads and compresses image for optimized icon caching * @param image_url/* w ww . j ava 2 s . com*/ * @return */ public static byte[] cacheImage(String image_url, Context sContext) { try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); InputStream caInput = sContext.getResources().openRawResource(R.raw.aware); Certificate ca; try { ca = cf.generateCertificate(caInput); } finally { caInput.close(); } KeyStore sKeyStore = KeyStore.getInstance(KeyStore.getDefaultType()); InputStream inStream = sContext.getResources().openRawResource(R.raw.awareframework); sKeyStore.load(inStream, "awareframework".toCharArray()); inStream.close(); sKeyStore.setCertificateEntry("ca", ca); String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(sKeyStore); SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); //Fetch image now that we recognise SSL URL image_path = new URL(image_url.replace("http://", "https://")); //make sure we are fetching the images over https HttpsURLConnection image_connection = (HttpsURLConnection) image_path.openConnection(); image_connection.setSSLSocketFactory(context.getSocketFactory()); InputStream in_stream = image_connection.getInputStream(); Bitmap tmpBitmap = BitmapFactory.decodeStream(in_stream); ByteArrayOutputStream output = new ByteArrayOutputStream(); tmpBitmap.compress(Bitmap.CompressFormat.PNG, 100, output); return output.toByteArray(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (CertificateException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } return null; }
From source file:com.brienwheeler.apps.tomcat.TomcatBean.java
private void configureNetwork() throws Exception { if (port > 0) { tomcat.setPort(port);/*from w w w . j a va2 s . c o m*/ } else { tomcat.getService().removeConnector(tomcat.getConnector()); } if (sslPort > 0) { StringBuffer randomPass = new StringBuffer(); for (int i = 0; i < 10; i++) randomPass.append(characters.charAt((int) (characters.length() * Math.random()))); String keystorePass = randomPass.toString(); RSAPrivateKey privateKey = readKeyFile(); log.info("successfully read SSL private key from " + sslKeyFile.getAbsolutePath()); X509Certificate certificate = readCertFile(); log.info("successfully read SSL certificate from " + sslCertFile.getAbsolutePath()); KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(null); keyStore.setCertificateEntry("cert-alias", certificate); keyStore.setKeyEntry("key-alias", privateKey, keystorePass.toCharArray(), new Certificate[] { certificate }); File keyStoreFile = new File("tcks"); keyStore.store(new FileOutputStream(keyStoreFile), keystorePass.toCharArray()); Connector sslConnector = new Connector(); sslConnector.setPort(sslPort); sslConnector.setSecure(true); sslConnector.setScheme("https"); sslConnector.setAttribute("keystoreFile", keyStoreFile.getAbsolutePath()); sslConnector.setAttribute("keystorePass", keystorePass); sslConnector.setAttribute("clientAuth", "false"); sslConnector.setAttribute("sslProtocol", "TLS"); sslConnector.setAttribute("SSLEnabled", true); tomcat.getService().addConnector(sslConnector); } }
From source file:com.kixeye.kixmpp.client.KixmppClientTest.java
private SslContext createSslContext() throws Exception { Certificate cert;/* w w w . j av a 2s .c om*/ try (InputStream certStream = this.getClass().getResourceAsStream("/bogus_mina_tls.cert")) { KeyStore ks = KeyStore.getInstance("JKS"); ks.load(certStream, "boguspw".toCharArray()); cert = ks.getCertificate("bogus"); } File certFile = File.createTempFile(UUID.randomUUID().toString().replace("-", ""), null); FileOutputStream certFileOutputStream = new FileOutputStream(certFile); IOUtils.copy(new StringReader("-----BEGIN CERTIFICATE-----\n"), certFileOutputStream); IOUtils.copy(new ByteArrayInputStream(Base64.encodeBase64(cert.getEncoded())), certFileOutputStream); IOUtils.copy(new StringReader("\n-----END CERTIFICATE-----"), certFileOutputStream); certFileOutputStream.close(); return SslContext.newClientContext(certFile); }
From source file:org.ocsinventoryng.android.actions.OCSProtocol.java
public DefaultHttpClient getNewHttpClient(boolean strict) { try {//from ww w .ja v a2s . com SSLSocketFactory sf; if (strict) { sf = SSLSocketFactory.getSocketFactory(); } else { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); sf = new CoolSSLSocketFactory(trustStore); } HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", sf, 443)); ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); HttpConnectionParams.setConnectionTimeout(params, 10000); HttpConnectionParams.setSoTimeout(params, 10000); return new DefaultHttpClient(ccm, params); } catch (Exception e) { return new DefaultHttpClient(); } }
From source file:com.geekandroid.sdk.pay.utils.Util.java
private static HttpClient getNewHttpClient() { try {/*w ww . j a v a2 s .c o m*/ KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", sf, 443)); ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); return new DefaultHttpClient(ccm, params); } catch (Exception e) { return new DefaultHttpClient(); } }