List of usage examples for java.security KeyStore getInstance
public static KeyStore getInstance(String type) throws KeyStoreException
From source file:org.jwebsocket.sso.HTTPSupport.java
/** * * @param aURL/* w w w . ja v a 2 s.c o m*/ * @param aMethod * @param aHeaders * @param aPostBody * @param aTimeout * @return */ public static String request(String aURL, String aMethod, Map<String, String> aHeaders, String aPostBody, long aTimeout) { if (mLog.isDebugEnabled()) { mLog.debug("Requesting (" + aMethod + ") '" + aURL + "', timeout: " + aTimeout + "ms, Headers: " + aHeaders + ", Body: " + (null != aPostBody ? "'" + aPostBody.replace("\n", "\\n").replace("\r", "\\r") + "'" : "[null]")); } String lResponse = "{\"code\": -1, \"msg\": \"undefined\""; try { KeyStore lTrustStore = KeyStore.getInstance(KeyStore.getDefaultType()); lTrustStore.load(null, null); // Trust own CA and all self-signed certs SSLContext lSSLContext = SSLContexts.custom() .loadTrustMaterial(lTrustStore, new TrustSelfSignedStrategy()).build(); // Allow TLSv1 protocol only SSLConnectionSocketFactory lSSLFactory = new SSLConnectionSocketFactory(lSSLContext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); CloseableHttpClient lHTTPClient = HttpClients.custom().setSSLSocketFactory(lSSLFactory).build(); HttpUriRequest lRequest; if ("POST".equals(aMethod)) { lRequest = new HttpPost(aURL); ((HttpPost) lRequest).setEntity(new ByteArrayEntity(aPostBody.getBytes("UTF-8"))); } else { lRequest = new HttpGet(aURL); } for (Map.Entry<String, String> lEntry : aHeaders.entrySet()) { lRequest.setHeader(lEntry.getKey(), lEntry.getValue()); } // System.out.println("Executing request " + lRequest.getRequestLine()); // Create a custom response handler ResponseHandler<String> lResponseHandler = new ResponseHandler<String>() { @Override public String handleResponse(final HttpResponse lResponse) throws ClientProtocolException, IOException { int lStatus = lResponse.getStatusLine().getStatusCode(); HttpEntity lEntity = lResponse.getEntity(); return lEntity != null ? EntityUtils.toString(lEntity) : null; // if (lStatus >= 200 && lStatus < 300) { // HttpEntity entity = lResponse.getEntity(); // return entity != null ? EntityUtils.toString(entity) : null; // } else { // throw new ClientProtocolException("Unexpected response status: " + lStatus); // } } }; long lStartedAt = System.currentTimeMillis(); lResponse = lHTTPClient.execute(lRequest, lResponseHandler); if (mLog.isDebugEnabled()) { mLog.debug("Response (" + (System.currentTimeMillis() - lStartedAt) + "ms): '" + lResponse.replace("\n", "\\n").replace("\r", "\\r") + "'"); } return lResponse; } catch (Exception lEx) { String lMsg = "{\"code\": -1, \"msg\": \"" + lEx.getClass().getSimpleName() + " at http request: " + lEx.getMessage() + "\"}"; mLog.error(lEx.getClass().getSimpleName() + ": " + lEx.getMessage() + ", returning: " + lMsg); lResponse = lMsg; return lResponse; } }
From source file:org.everit.authentication.cas.ecm.tests.SecureHttpClient.java
/** * Constructor./*w w w .j a va 2 s . c o m*/ */ public SecureHttpClient(final String principal, final BundleContext bundleContext) throws Exception { this.principal = principal; httpClientContext = HttpClientContext.create(); httpClientContext.setCookieStore(new BasicCookieStore()); KeyStore trustStore = KeyStore.getInstance("jks"); trustStore.load(bundleContext.getBundle().getResource("/jetty-keystore").openStream(), "changeit".toCharArray()); TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(trustStore); TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, trustManagers, new SecureRandom()); httpClient = HttpClientBuilder.create().setSslcontext(sslContext) .setRedirectStrategy(new DefaultRedirectStrategy()).build(); }
From source file:ddf.security.common.util.CommonSSLFactory.java
/** * Creates a new SSLSocketFactory from a truststore and keystore. This is used during SSL * communication.//from ww w . j a v a 2 s . c om * * @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 IOException */ public static SSLSocketFactory createSocket(String trustStoreLoc, String trustStorePass, String keyStoreLoc, String keyStorePass) throws IOException { String methodName = "createSocket"; logger.debug("ENTERING: " + methodName); try { 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()); } catch (CertificateException e) { throw new IOException("Unable to load certificates from truststore. " + trustStoreLoc, e); } 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()); } catch (CertificateException e) { throw new IOException("Unable to load certificates from keystore. " + keyStoreLoc, e); } 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); sslCtx.getDefaultSSLParameters().setNeedClientAuth(true); sslCtx.getDefaultSSLParameters().setWantClientAuth(true); logger.debug(exiting + methodName); return sslCtx.getSocketFactory(); } catch (KeyManagementException e) { logger.debug(exiting + methodName); throw new IOException("Unable to initialize the SSL context.", e); } catch (NoSuchAlgorithmException e) { logger.debug(exiting + methodName); throw new IOException( "Problems creating SSL socket. Usually this is " + "referring to the certificate sent by the server not being trusted by the client.", e); } catch (UnrecoverableKeyException e) { logger.debug(exiting + methodName); throw new IOException("Unable to load keystore. " + keyStoreLoc, e); } catch (KeyStoreException e) { logger.debug(exiting + methodName); throw new IOException("Unable to read keystore. " + keyStoreLoc, e); } }
From source file:com.navnorth.learningregistry.LRClient.java
public static HttpClient getHttpClient(String scheme) { // TODO: this allows for self-signed certificates, which should just be an option, not used by default. if (scheme.equals("https")) { try {/*from w ww.j av a2 s. c om*/ KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); SSLSocketFactory sf = new SelfSignSSLSocketFactory(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(); } } else { return new DefaultHttpClient(); } }
From source file:net.sf.hajdbc.codec.crypto.CipherCodecFactoryTest.java
@Before public void before() throws Exception { File file = File.createTempFile("ha-jdbc", "keystore"); SecretKeyFactory factory = SecretKeyFactory.getInstance(ALGORITHM); this.key = factory.generateSecret(new DESKeySpec(Base64.decodeBase64(KEY.getBytes()))); KeyStore store = KeyStore.getInstance(CipherCodecFactory.Property.KEYSTORE_TYPE.defaultValue); store.load(null, null);/*ww w . java 2s . co m*/ store.setKeyEntry(CipherCodecFactory.Property.KEY_ALIAS.defaultValue, this.key, KEY_PASSWORD.toCharArray(), null); FileOutputStream out = new FileOutputStream(file); try { store.store(out, STORE_PASSWORD.toCharArray()); } finally { Resources.close(out); } System.setProperty(CipherCodecFactory.Property.KEYSTORE_FILE.name, file.getPath()); System.setProperty(CipherCodecFactory.Property.KEYSTORE_PASSWORD.name, STORE_PASSWORD); System.setProperty(CipherCodecFactory.Property.KEY_PASSWORD.name, KEY_PASSWORD); }
From source file:mobisocial.musubi.util.CertifiedHttpClient.java
private SSLSocketFactory newSslSocketFactory() { try {//from w w w . j a va2 s . c o m KeyStore trusted = KeyStore.getInstance("BKS"); InputStream in = mContext.getResources().openRawResource(R.raw.servercertificates); try { trusted.load(in, "ez24get".toCharArray()); } finally { in.close(); } SSLSocketFactory sf = new SSLSocketFactory(trusted); //don't check the host name because we are doing funny redirects. the //actual cert is good enough because it is bundled. sf.setHostnameVerifier(new AllowAllHostnameVerifier()); return sf; } catch (Exception e) { throw new AssertionError(e); } }
From source file:nl.surfnet.mujina.model.SpConfigurationImpl.java
@Override public void reset() { entityId = "http://mock-sp"; setSigning(false);/* ww w .j ava 2s . co m*/ try { keyStore = KeyStore.getInstance("JKS"); keyStore.load(null, keystorePassword.toCharArray()); KeyStoreUtil.appendKeyToKeyStore(keyStore, "http://mock-sp", new ClassPathResource("idp-crt.pem").getInputStream(), new ClassPathResource("idp-key.pkcs8.der").getInputStream(), keystorePassword.toCharArray()); privateKeyPasswords.put("http://mock-sp", keystorePassword); idpSSOServiceURL = defaultIdpSSOServiceURL; protocolBinding = defaultProtocolBinding; assertionConsumerServiceURL = defaultAssertionConsumerServiceURL; } catch (Exception e) { log.error("Unable to create default keystore", e); } }
From source file:eu.europa.esig.dss.cookbook.sources.JavaKeyStoreTool.java
public JavaKeyStoreTool(final String ksUrlLocation, final String ksPassword) { InputStream ksStream = null;//from w w w .j a va2 s . c o m try { final URL ksLocation = new URL(ksUrlLocation); ks = KeyStore.getInstance(KeyStore.getDefaultType()); ksStream = ksLocation.openStream(); ks.load(ksStream, (ksPassword == null) ? null : ksPassword.toCharArray()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (CertificateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(ksStream); } }
From source file:gobblin.security.ssl.SSLContextFactory.java
/** * Create a {@link SSLContext} instance/* ww w .j a v a 2 s .c o m*/ * * @param keyStoreFile a p12 or jks file depending on key store type * @param keyStorePassword password to access the key store * @param keyStoreType type of key store * @param trustStoreFile a jks file * @param trustStorePassword password to access the trust store */ public static SSLContext createInstance(File keyStoreFile, String keyStorePassword, String keyStoreType, File trustStoreFile, String trustStorePassword) { if (!keyStoreType.equalsIgnoreCase(P12_STORE_TYPE_NAME) && !keyStoreType.equalsIgnoreCase(JKS_STORE_TYPE_NAME)) { throw new IllegalArgumentException("Unsupported keyStoreType: " + keyStoreType); } try { // Load KeyStore KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(toInputStream(keyStoreFile), keyStorePassword.toCharArray()); // Load TrustStore KeyStore trustStore = KeyStore.getInstance(JKS_STORE_TYPE_NAME); trustStore.load(toInputStream(trustStoreFile), trustStorePassword.toCharArray()); // Set KeyManger from keyStore KeyManagerFactory kmf = KeyManagerFactory.getInstance(DEFAULT_ALGORITHM); kmf.init(keyStore, keyStorePassword.toCharArray()); // Set TrustManager from trustStore TrustManagerFactory trustFact = TrustManagerFactory.getInstance(DEFAULT_ALGORITHM); trustFact.init(trustStore); // Set Context to TLS and initialize it SSLContext sslContext = SSLContext.getInstance(DEFAULT_PROTOCOL); sslContext.init(kmf.getKeyManagers(), trustFact.getTrustManagers(), null); return sslContext; } catch (Exception e) { throw new RuntimeException(e); } }