List of usage examples for java.security KeyStore load
public final void load(InputStream stream, char[] password) throws IOException, NoSuchAlgorithmException, CertificateException
From source file:energy.usef.environment.tool.security.KeystoreService.java
public static void createNewStoreIfNeeded(String fileName, char[] keystorePassword) throws KeyStoreException, NoSuchAlgorithmException, CertificateException { File file = new File(fileName); if (file != null && file.exists()) { return;/*from ww w . ja v a 2s . co m*/ } KeyStore ks = KeyStore.getInstance(JCEKS); try (OutputStream os = new FileOutputStream(fileName)) { ks.load(null, keystorePassword); ks.store(os, keystorePassword); } catch (IOException e) { LOGGER.error("Error while creating the Keystore: {}. Keystore will not be created." + e.getMessage() + "\n" + e); throw new RuntimeException(e); } }
From source file:com.cloudera.nav.sdk.client.SSLUtils.java
private static X509TrustManager loadTrustManager(String type, String file, String password) throws IOException, GeneralSecurityException { X509TrustManager trustManager = null; KeyStore ks = KeyStore.getInstance(type); try (FileInputStream in = new FileInputStream(file)) { ks.load(in, password.toCharArray()); LOG.debug("Loaded truststore '" + file + "'"); }//ww w . jav a 2s.co m TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(SSLCERTIFICATE); trustManagerFactory.init(ks); TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); for (TrustManager trustManager1 : trustManagers) { if (trustManager1 instanceof X509TrustManager) { trustManager = (X509TrustManager) trustManager1; break; } } return trustManager; }
From source file:com.oneis.common.utils.SSLCertificates.java
public static SSLContext load(String keysDirectory, String certsName, String clientCAName, boolean quiet) throws Exception { // For some indiciation of what's going on early in the boot process if (!quiet) { System.out.println("Loading " + certsName + " SSL certificates from " + keysDirectory); }//w w w. java 2 s.c o m // Get filenames String keyPathname = keysDirectory + "/" + certsName + ".key"; String certPathname = keysDirectory + "/" + certsName + ".crt"; final String intermediateCertPathnameBase = keysDirectory + "/" + certsName + "-intermediate"; String clientCAPathname = null; if (clientCAName != null) { clientCAPathname = keysDirectory + "/" + clientCAName + ".crt"; } if (!new File(keyPathname).exists()) { System.out.println("Doesn't exist: " + keyPathname); return null; } if (!new File(certPathname).exists()) { System.out.println("Doesn't exist: " + certPathname); return null; } if (clientCAPathname != null) { if (!new File(clientCAPathname).exists()) { System.out.println("Doesn't exist: " + clientCAPathname); return null; } } char[] nullPassword = {}; PrivateKey privateKey = readPEMPrivateKey(keyPathname); CertificateFactory cf = CertificateFactory.getInstance("X.509"); // Server certificate ArrayList<java.security.cert.Certificate> certList = new ArrayList<java.security.cert.Certificate>(4); java.security.cert.Certificate cert = cf.generateCertificate(readPEM(certPathname)); certList.add(cert); // Optional intermediate certificates int intermediateCounter = 1; while (true) { String intermediateCertPathname = intermediateCertPathnameBase; if (intermediateCounter != 1) { intermediateCertPathname += "-" + intermediateCounter; } intermediateCounter++; intermediateCertPathname += ".crt"; if (new File(intermediateCertPathname).exists()) { certList.add(cf.generateCertificate(readPEM(intermediateCertPathname))); } else { // End of cert list break; } } // Optional client CA certificate java.security.cert.Certificate clientCACert = null; if (clientCAPathname != null) { clientCACert = cf.generateCertificate(readPEM(clientCAPathname)); } if (clientCAName != null && clientCACert == null) { throw new RuntimeException("Logic error, failed to load client CA cert when required"); } KeyStore ks = KeyStore.getInstance("JKS", "SUN"); ks.load(null, nullPassword); ks.setKeyEntry("ONEIS", (Key) privateKey, "".toCharArray(), certList.toArray(new java.security.cert.Certificate[certList.size()])); if (clientCACert != null) { KeyStore.TrustedCertificateEntry tce = new KeyStore.TrustedCertificateEntry(clientCACert); ks.setEntry("CLIENTCA", tce, null); } // Generate some random Java API stuff, just for entertainment KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); kmf.init(ks, nullPassword); TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); tmf.init(ks); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); if (!quiet) { System.out.println(" - server cert chain length " + certList.size() + (clientCACert != null ? ", requires client cert" : ", public server")); } return sslContext; }
From source file:com.ecofactor.qa.automation.consumerapi.dr.HTTPSClient.java
/** * Gets the http client.//from w w w . j a v a2 s .c om * * @param certificate the certificate * @param password the password * @return the http client */ public static CloseableHttpClient getPKCSKeyHttpClient(final String certificate, final String password) { try { final KeyStore keystore = KeyStore.getInstance("pkcs12"); keystore.load(HTTPSClient.class.getClassLoader().getResourceAsStream(certificate), password.toCharArray()); final SSLContextBuilder builder = new SSLContextBuilder(); builder.loadKeyMaterial(keystore, password.toCharArray()); final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build()); final CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf) .setHostnameVerifier(new AllowAllHostnameVerifier()).build(); return httpClient; } catch (UnrecoverableKeyException | KeyManagementException | KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException e) { LOGGER.error("Error processing SSL certificates in HTTPS method. Reason ::: " + e); return null; } }
From source file:org.structr.android.restclient.StructrConnector.java
private static SSLSocketFactory createSslSocketFactory(Context context, int resourceId, String keyStorePassword) { try {/*from w ww . j av a 2 s .co m*/ KeyStore trusted = KeyStore.getInstance("BKS"); InputStream in = context.getResources().openRawResource(resourceId); try { trusted.load(in, keyStorePassword.toCharArray()); } finally { in.close(); } return new SSLSocketFactory(trusted); } catch (Exception e) { throw new AssertionError(e); } }
From source file:com.deying.util.weixin.ClientCustomSSL.java
public static String doRefund(String url, String data) throws Exception { System.out.println("111111111111111111111111111111111111111111111118 "); KeyStore keyStore = KeyStore.getInstance("PKCS12"); FileInputStream instream = new FileInputStream(new File("E:/apiclient_cert.p12"));//P12 try {// www. j a v a 2 s .c o m keyStore.load(instream, "1233374102".toCharArray());//?..MCHID } finally { instream.close(); } // Trust own CA and all self-signed certs SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, "1233374102".toCharArray())//? .build(); // Allow TLSv1 protocol only SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); try { HttpPost httpost = new HttpPost(url); // ?? httpost.addHeader("Connection", "keep-alive"); httpost.addHeader("Accept", "*/*"); httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); httpost.addHeader("Host", "api.mch.weixin.qq.com"); httpost.addHeader("X-Requested-With", "XMLHttpRequest"); httpost.addHeader("Cache-Control", "max-age=0"); httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) "); httpost.setEntity(new StringEntity(data, "UTF-8")); CloseableHttpResponse response = httpclient.execute(httpost); try { HttpEntity entity = response.getEntity(); String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8"); EntityUtils.consume(entity); return jsonStr; } finally { response.close(); } } finally { httpclient.close(); } }
From source file:eu.trentorise.smartcampus.ac.network.HttpsClientBuilder.java
private static HttpClient getWildcartHttpClient(HttpParams inParams) { HttpClient client = null;/*from w w w .ja va2 s. c om*/ HttpParams params = inParams != null ? inParams : new BasicHttpParams(); try { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); SSLSocketFactory sslSocketFactory = new CustomSSLSocketFactory(trustStore); final X509HostnameVerifier delegate = sslSocketFactory.getHostnameVerifier(); if (!(delegate instanceof WildcardVerifier)) { sslSocketFactory.setHostnameVerifier(new WildcardVerifier(delegate)); } registry.register(new Scheme("https", sslSocketFactory, 443)); ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); client = new DefaultHttpClient(ccm, params); } catch (Exception e) { client = new DefaultHttpClient(params); } return client; }
From source file:eu.trentorise.smartcampus.ac.network.HttpsClientBuilder.java
private static HttpClient getAcceptAllHttpClient(HttpParams inParams) { HttpClient client = null;/*www . j ava 2 s. co m*/ HttpParams params = inParams != null ? inParams : new BasicHttpParams(); try { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); // IMPORTANT: use CustolSSLSocketFactory for 2.2 SSLSocketFactory sslSocketFactory = new SSLSocketFactory(trustStore); if (android.os.Build.VERSION.SDK_INT <= android.os.Build.VERSION_CODES.FROYO) { sslSocketFactory = new CustomSSLSocketFactory(trustStore); } sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); registry.register(new Scheme("https", sslSocketFactory, 443)); ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); client = new DefaultHttpClient(ccm, params); } catch (Exception e) { client = new DefaultHttpClient(params); } return client; }
From source file:cn.dacas.emmclient.security.ssl.EasySSLSocketFactory.java
private static SSLContext createEasySSLContext() throws IOException { try {//from ww w . j a va 2 s . c o m // Client should authenticate itself with the valid certificate to Server. InputStream clientStream = EmmClientApplication.getContext().getResources() .openRawResource(R.raw.production_test_client); char[] password = "XXXXXXXXXXXXX".toCharArray(); KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load(clientStream, password); KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keyStore, password); // Client should also add the CA certificate obtained from server and create TrustManager from it for the client to validate the // identity of the server. KeyStore trustStore = KeyStore.getInstance("BKS"); InputStream instream = null; instream = EmmClientApplication.getContext().getResources().openRawResource(R.raw.production_test_ca); try { trustStore.load(instream, "XXXXXXXX".toCharArray()); } catch (Exception e) { e.printStackTrace(); } finally { try { instream.close(); } catch (Exception ignore) { } } String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(trustStore); // Create an SSLContext that uses our TrustManager & Keystore SSLContext context = SSLContext.getInstance("TLS"); context.init(keyManagerFactory.getKeyManagers(), tmf.getTrustManagers(), null); return context; } catch (Exception e) { e.printStackTrace(); throw new IOException(e.getMessage()); } }
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 ava2s .com*/ 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(); } }