List of usage examples for java.security KeyStore load
public final void load(InputStream stream, char[] password) throws IOException, NoSuchAlgorithmException, CertificateException
From source file:test.SAMLAttributeQueryExample.java
/** * Build the HTTP client.//from w w w . j av a2 s .c o m * * @param idpCertificateFile path to idp certificate file * @param clientPrivateKeyFile path to client private key file * @param clientCertificateFile path to client certificate file * @return the HTTP client * @throws Exception if an error occurs */ @Nonnull public static HttpClient buildHttpClient(@Nonnull final String idpCertificateFile, @Nonnull final String clientPrivateKeyFile, @Nonnull final String clientCertificateFile) throws Exception { X509Certificate idpCert = CertUtil.readCertificate(idpCertificateFile); KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); trustStore.setCertificateEntry("idp", idpCert); PrivateKey clientPrivateKey = KeyPairUtil.readPrivateKey(clientPrivateKeyFile); X509Certificate clientCert = CertUtil.readCertificate(clientCertificateFile); KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, null); keyStore.setKeyEntry("me", clientPrivateKey, "secret".toCharArray(), new Certificate[] { clientCert }); SSLContextBuilder sslContextBuilder = SSLContexts.custom(); sslContextBuilder.loadTrustMaterial(trustStore); sslContextBuilder.loadKeyMaterial(keyStore, "secret".toCharArray()); SSLContext sslcontext = sslContextBuilder.build(); CloseableHttpClient httpClient = HttpClients.custom().setSslcontext(sslcontext).build(); return httpClient; }
From source file:com.baasbox.android.HttpUrlConnectionClient.java
private static SSLSocketFactory createSocketFactory(Context context, int certStoreId, String certPassword) { TrustManagerFactory tmf;/*ww w. j a v a 2 s . co m*/ InputStream in = null; try { in = context.getResources().openRawResource(certStoreId); KeyStore keyStore = KeyStore.getInstance("BKS"); keyStore.load(in, certPassword.toCharArray()); tmf = TrustManagerFactory.getInstance("X509"); tmf.init(keyStore); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, tmf.getTrustManagers(), null); return sslContext.getSocketFactory(); } catch (Exception e) { throw new BaasRuntimeException(e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { // swallow } } } }
From source file:ddf.security.common.util.CommonSSLFactory.java
/** * Creates a new SSLSocketFactory from a truststore and keystore. This is used during SSL * communication.//w w w.j a v a2s . 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.pispower.video.sdk.net.SimpleSSLSocketFactory.java
/** * Gets a DefaultHttpClient which trusts a set of certificates specified by * the KeyStore//from w ww . ja va 2 s .co m * * @param keyStore * custom provided KeyStore instance * @return DefaultHttpClient */ public static DefaultHttpClient getDefaultHttpClient() { try { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); SSLSocketFactory sf = new SimpleSSLSocketFactory(trustStore); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", sf, 443)); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); return new DefaultHttpClient(ccm, params); } catch (Exception e) { return new DefaultHttpClient(); } }
From source file:eidassaml.starterkit.Utils.java
/** * // w w w . ja va 2 s .c om * @param stream * @param password * @param alias * @return * @throws KeyStoreException * @throws NoSuchAlgorithmException * @throws CertificateException * @throws IOException * @throws UnrecoverableKeyException * @throws NoSuchProviderException */ public static X509KeyPair ReadPKCS12(InputStream stream, char[] password, String alias) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException, NoSuchProviderException { KeyStore p12 = KeyStore.getInstance("pkcs12", "BC"); p12.load(stream, password); Enumeration<String> e = p12.aliases(); PrivateKey key = null; X509Certificate cert = null; StringBuffer aliasBuf = new StringBuffer(); while (e.hasMoreElements()) { String currentalias = (String) e.nextElement(); aliasBuf.append(currentalias); aliasBuf.append(" ||| "); cert = (X509Certificate) p12.getCertificate(currentalias); key = (PrivateKey) p12.getKey(currentalias, password); if (Utils.IsNullOrEmpty(alias) && key != null) { //take the first one break; } else if (currentalias.equals(alias) && key != null) { break; } } if (key != null) { return new X509KeyPair(key, cert); } else { StringBuffer errbuf = new StringBuffer(); errbuf.append("keystore does not contains alias " + alias + ". Try alias " + aliasBuf.toString()); throw new KeyStoreException(errbuf.toString()); } }
From source file:com.shwy.bestjoy.utils.AndroidHttpClient.java
/** * Create a new HttpClient with reasonable defaults (which you can update). * * @param userAgent to report in your HTTP requests. * @return AndroidHttpClient for you to use for all your requests. *///from www. ja v a 2 s . co m public static HttpClient newInstance(String userAgent) { try { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); SSLSocketFactory sslSocketFactory = new SSLSocketFactoryEx(trustStore); sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); HttpParams params = new BasicHttpParams(); // Turn off stale checking. Our connections break all the time anyway, // and it's not worth it to pay the penalty of checking every time. HttpConnectionParams.setStaleCheckingEnabled(params, false); // Default connection and socket timeout of 20 seconds. Tweak to taste. HttpConnectionParams.setConnectionTimeout(params, 60 * 1000); HttpConnectionParams.setSoTimeout(params, 60 * 1000); HttpConnectionParams.setSocketBufferSize(params, 8192); // Don't handle redirects -- return them to the caller. Our code // often wants to re-POST after a redirect, which we must do ourselves. HttpClientParams.setRedirecting(params, true); // Set the specified user agent and register standard protocols. HttpProtocolParams.setUserAgent(params, userAgent); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); schemeRegistry.register(new Scheme("https", sslSocketFactory, 443)); ClientConnectionManager manager = new ThreadSafeClientConnManager(params, schemeRegistry); // We use a factory method to modify superclass initialization // parameters without the funny call-a-static-method dance. return new AndroidHttpClient(manager, params); } catch (KeyStoreException e) { e.printStackTrace(); } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (UnrecoverableKeyException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } return new DefaultHttpClient(); }
From source file:com.shalzz.attendance.wrapper.MySSLSocketFactory.java
/** * Gets a KeyStore containing the Certificate * /* w w w . ja v a 2s. c o m*/ * @param cert InputStream of the Certificate * @return KeyStore */ public static KeyStore getKeystoreOfCA(InputStream cert) { // Load CAs from an InputStream InputStream caInput = null; Certificate ca = null; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); caInput = new BufferedInputStream(cert); ca = cf.generateCertificate(caInput); } catch (CertificateException e1) { e1.printStackTrace(); } finally { try { caInput.close(); } catch (IOException e) { e.printStackTrace(); } } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = null; try { keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("ca", ca); } catch (Exception e) { e.printStackTrace(); } return keyStore; }
From source file:com.spacetimeinsight.webservice.ssl.EasySSLProtocolSocketFactory.java
public static SSLContext getContext(File pKeyFile, String pKeyPassword) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException, UnrecoverableKeyException, KeyManagementException { KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509"); KeyStore keyStore = KeyStore.getInstance("PKCS12"); InputStream keyInput = new FileInputStream(pKeyFile); try {/*from w w w .ja v a 2 s. c o m*/ keyStore.load(keyInput, pKeyPassword.toCharArray()); } catch (java.security.cert.CertificateException e) { // TODO Auto-generated catch block e.printStackTrace(); } keyInput.close(); keyManagerFactory.init(keyStore, pKeyPassword.toCharArray()); TrustManager[] trustAllCerts = new TrustManager[] { (X509TrustManager) new EasyX509SSLTrustManager(keyStore) }; // javax.net.ssl.SSLContext context = javax.net.ssl.getInstance("SSL"); SSLContext context = SSLContext.getInstance("SSL"); context.init(keyManagerFactory.getKeyManagers(), trustAllCerts, new SecureRandom()); return context; }
From source file:org.zywx.wbpalmstar.platform.certificates.Http.java
public static HNetSSLSocketFactory getSSLSocketFactoryWithCert(String cPassWord, String cPath, Context ctx) { InputStream inStream = null;//www. j ava 2 s.c o m HNetSSLSocketFactory ssSocketFactory = null; try { int index = cPath.lastIndexOf('/'); String keyName = cPath.substring(index); KeyStore ksP12 = KEY_STORE.get(keyName); if (null == ksP12) { inStream = getInputStream(cPath, ctx); ksP12 = KeyStore.getInstance("pkcs12"); ksP12.load(inStream, cPassWord.toCharArray()); KEY_STORE.put(keyName, ksP12); } ssSocketFactory = new HNetSSLSocketFactory(ksP12, cPassWord); } catch (Exception e) { e.printStackTrace(); ssSocketFactory = getSSLSocketFactory(); } return ssSocketFactory; }
From source file:com.jeecms.common.web.ClientCustomSSL.java
public static String getInSsl(String url, File pkcFile, String storeId, String params, String contentType) throws Exception { String text = ""; // ???PKCS12/* w ww.j av a 2 s. c om*/ KeyStore keyStore = KeyStore.getInstance("PKCS12"); // ?PKCS12? FileInputStream instream = new FileInputStream(pkcFile); try { // PKCS12?(ID) keyStore.load(instream, storeId.toCharArray()); } finally { instream.close(); } // Trust own CA and all self-signed certs SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, storeId.toCharArray()).build(); // Allow TLSv1 protocol only // TLS SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); // httpclientSSLSocketFactory CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); try { HttpPost post = new HttpPost(url); StringEntity s = new StringEntity(params, "utf-8"); if (StringUtils.isBlank(contentType)) { s.setContentType("application/xml"); } s.setContentType(contentType); post.setEntity(s); HttpResponse res = httpclient.execute(post); HttpEntity entity = res.getEntity(); text = EntityUtils.toString(entity, "utf-8"); } finally { httpclient.close(); } return text; }