List of usage examples for java.security KeyStore getInstance
public static KeyStore getInstance(String type) throws KeyStoreException
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 w ww . ja v 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:io.kodokojo.config.module.SecurityModule.java
@Provides @Singleton//from w ww . ja v a 2 s . c o m SSLKeyPair provideSSLKeyPair(SecurityConfig securityConfig) { if (securityConfig == null) { throw new IllegalArgumentException("securityConfig must be defined."); } if (StringUtils.isNotBlank(securityConfig.wildcardPemPath())) { File pemFile = new File(securityConfig.wildcardPemPath()); try { String content = IOUtils.toString(new FileReader(pemFile)); String contentPrivate = RSAUtils.extractPrivateKey(content); String contentPublic = RSAUtils.extractPublic(content); RSAPrivateKey rsaPrivateKey = RSAUtils.readRsaPrivateKey(new StringReader(contentPrivate)); X509Certificate certificate = RSAUtils.readRsaPublicKey(new StringReader(contentPublic)); RSAPublicKey rsaPublicKey = (RSAPublicKey) certificate.getPublicKey(); X509Certificate[] certificates = new X509Certificate[1]; certificates[0] = certificate; LOGGER.info( "Using Wildcard SSL certificat {} from path {}to provide Certificat to all instances of Kodo Kojo. ", certificate.getSubjectDN().toString(), securityConfig.wildcardPemPath()); return new SSLKeyPair(rsaPrivateKey, rsaPublicKey, certificates); } catch (IOException e) { throw new IllegalArgumentException("Unable to read pem file " + pemFile.getAbsolutePath() + ".", e); } } else { try { KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(new FileInputStream(System.getProperty("javax.net.ssl.keyStore")), System.getProperty("javax.net.ssl.keyStorePassword", "").toCharArray()); RSAPrivateCrtKey key = (RSAPrivateCrtKey) ks.getKey(securityConfig.sslRootCaKsAlias(), securityConfig.sslRootCaKsPassword().toCharArray()); if (key == null) { return null; } RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(key.getModulus(), key.getPublicExponent()); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(publicKeySpec); Certificate[] certificateChain = ks.getCertificateChain(securityConfig.sslRootCaKsAlias()); List<X509Certificate> x509Certificates = Arrays.asList(certificateChain).stream() .map(c -> (X509Certificate) c).collect(Collectors.toList()); LOGGER.info( "Using a CA SSL certificat {} from keystore to provide Certificat to all instances of Kodo Kojo. ", securityConfig.sslRootCaKsAlias(), System.getProperty("javax.net.ssl.keyStore")); return new SSLKeyPair(key, publicKey, x509Certificates.toArray(new X509Certificate[x509Certificates.size()])); } catch (UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException | InvalidKeySpecException | CertificateException | IOException e) { throw new RuntimeException("Unable to open default Keystore", e); } } }
From source file:hu.balazsbakai.sq.util.RestUtil.java
private DefaultHttpClient getNewTrustedHttpClient() { try {//from w w w . ja va 2s. co m KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); SSLSocketFactory sf = new CustomTrustedSSLSocketFactory(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); HttpConnectionParams.setConnectionTimeout(params, CONNECTION_TIMEOUT); HttpConnectionParams.setSoTimeout(params, SOCKET_TIMEOUT); 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) { LogUtil.e("Exception", e); return new DefaultHttpClient(); } }
From source file:com.mymed.android.myjam.controller.CallManager.java
protected SchemeRegistry createSchemeRegistry(Context context) { InputStream certInStream = context.getResources().openRawResource(R.raw.mymed_truststore); SchemeRegistry schemeRegistry = new SchemeRegistry(); // Create and initialize scheme registry schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); SSLSocketFactory sslf = null; try {/*w w w .j a va 2 s.c om*/ KeyStore mymedTrusted = KeyStore.getInstance("BKS"); mymedTrusted.load(certInStream, "alcotra".toCharArray()); sslf = new SSLSocketFactory(mymedTrusted); sslf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); } catch (KeyStoreException e) { Log.e(TAG, "Wrong keystore type.", e); } catch (KeyManagementException e) { Log.e(TAG, "Error creating SSLSocketFactory.", e); } catch (NoSuchAlgorithmException e) { Log.e(TAG, "Error creating SSLSocketFactory.", e); } catch (UnrecoverableKeyException e) { Log.e(TAG, "Error creating SSLSocketFactory.", e); } catch (CertificateException e) { Log.e(TAG, "Error loading keystore certificate.", e); } catch (IOException e) { Log.e(TAG, "Error creating scheme registry.", e); } finally { if (sslf != null) { schemeRegistry.register(new Scheme("https", sslf, 8081)); } try { certInStream.close(); } catch (IOException e) { Log.e(TAG, "Error closing the certificate stream.", e); } } return schemeRegistry; }
From source file:cn.com.mozilla.sync.utils.HttpsTransport.java
public HttpsTransport() { // Create SSL socket factory if (ALLOW_INVALID_CERTS) { try {//from w w w . j av a 2 s . co m KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); mSslSocketFactory = new EasySSLSocketFactory(trustStore); } catch (GeneralSecurityException e) { Log.w("Firefoxmini", e.toString()); } catch (IOException e) { Log.w("Firefoxmini", e.toString()); } } if (mSslSocketFactory == null) { mSslSocketFactory = SSLSocketFactory.getSocketFactory(); } // Create ClientConnectionManager SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("https", mSslSocketFactory, HTTPS_PORT_DEFAULT)); mClientConMgr = new SingleClientConnManager(sHttpParams, schemeRegistry); }
From source file:org.gw2InfoViewer.factories.HttpsConnectionFactory.java
public static HttpClient getHttpsClientWithProxy(byte[] sslCertificateBytes, String proxyAddress, int proxyPort) { DefaultHttpClient httpClient;/* www . j a v a2 s . co m*/ Certificate[] sslCertificate; HttpHost proxy; httpClient = new DefaultHttpClient(); try { sslCertificate = convertByteArrayToCertificate(sslCertificateBytes); TrustManagerFactory tf = TrustManagerFactory.getInstance("X509"); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(null); for (int i = 0; i < sslCertificate.length; i++) { ks.setCertificateEntry("StartCom" + i, sslCertificate[i]); } tf.init(ks); TrustManager[] tm = tf.getTrustManagers(); SSLContext sslCon = SSLContext.getInstance("SSL"); sslCon.init(null, tm, new SecureRandom()); SSLSocketFactory socketFactory = new SSLSocketFactory(ks); Scheme sch = new Scheme("https", 443, socketFactory); proxy = new HttpHost(proxyAddress, proxyPort, "https"); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); httpClient.getConnectionManager().getSchemeRegistry().register(sch); } catch (CertificateException | NoSuchAlgorithmException | KeyStoreException | IOException | KeyManagementException | UnrecoverableKeyException ex) { Logger.getLogger(HttpsConnectionFactory.class.getName()).log(Level.SEVERE, null, ex); } return httpClient; }
From source file:com.axelor.apps.account.ebics.client.HttpRequestSender.java
private DefaultHttpClient getSecuredHttpClient(Certificate cert) throws AxelorException { DefaultHttpClient client = new DefaultHttpClient(); try {//w ww . ja v a 2 s. c o m KeyStore keystore = KeyStore.getInstance("jks"); char[] password = "NoPassword".toCharArray(); keystore.load(null, password); keystore.setCertificateEntry("certficate.host", cert); Scheme https = new Scheme("https", 443, new SSLSocketFactory(keystore)); client.getConnectionManager().getSchemeRegistry().register(https); } catch (Exception e) { e.printStackTrace(); throw new AxelorException(I18n.get("Error adding certificate"), IException.TECHNICAL); } return client; }
From source file:org.hawkular.client.RestFactory.java
public HttpClient getHttpClient() { SSLContextBuilder builder = new SSLContextBuilder(); try {//from ww w. ja v a2 s . c o m KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); builder.loadTrustMaterial(keyStore, new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] trustedCert, String nameConstraints) throws CertificateException { return true; } }); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build()); CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); return httpclient; } catch (Exception ex) { _logger.error("Exception, ", ex); return null; } }
From source file:com.enioka.jqm.tools.JettyTest.java
@Test public void testSslClientCert() throws Exception { Helpers.setSingleParam("enableWsApiSsl", "true", em); Helpers.setSingleParam("disableWsApi", "false", em); Helpers.setSingleParam("enableWsApiAuth", "false", em); addAndStartEngine();/* w ww.ja va 2 s . co m*/ // Launch a job so as to be able to query its status later CreationTools.createJobDef(null, true, "App", null, "jqm-tests/jqm-test-datetimemaven/target/test.jar", TestHelpers.qVip, 42, "MarsuApplication", null, "Franquin", "ModuleMachin", "other", "other", true, em); JobRequest j = new JobRequest("MarsuApplication", "TestUser"); int i = JqmClientFactory.getClient().enqueue(j); TestHelpers.waitFor(1, 10000, em); // Server auth against trusted CA root certificate KeyStore trustStore = KeyStore.getInstance("JKS"); FileInputStream instream = new FileInputStream(new File("./conf/trusted.jks")); try { trustStore.load(instream, "SuperPassword".toCharArray()); } finally { instream.close(); } // Client auth JpaCa.prepareClientStore(em, "CN=testuser", "./conf/client.pfx", "SuperPassword", "client-cert", "./conf/client.cer"); KeyStore clientStore = KeyStore.getInstance("PKCS12"); instream = new FileInputStream(new File("./conf/client.pfx")); try { clientStore.load(instream, "SuperPassword".toCharArray()); } finally { instream.close(); } SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore) .loadKeyMaterial(clientStore, "SuperPassword".toCharArray()).build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); CloseableHttpClient cl = HttpClients.custom().setSSLSocketFactory(sslsf).build(); int port = em.createQuery("SELECT q.port FROM Node q WHERE q.id = :i", Integer.class) .setParameter("i", TestHelpers.node.getId()).getSingleResult(); HttpUriRequest rq = new HttpGet( "https://" + TestHelpers.node.getDns() + ":" + port + "/ws/simple/status?id=" + i); CloseableHttpResponse rs = cl.execute(rq); Assert.assertEquals(200, rs.getStatusLine().getStatusCode()); rs.close(); cl.close(); }