List of usage examples for java.security KeyStore load
public final void load(InputStream stream, char[] password) throws IOException, NoSuchAlgorithmException, CertificateException
From source file:com.emc.cto.ridagent.rid.test.TestScript.java
public static String httpSend(String output, String destURL) throws ParserConfigurationException, SAXException { /* Set up TLS mutual authentication */ KeyStore keystore = null; String docid = null;// ww w .ja v a 2s.com try { keystore = KeyStore.getInstance(KeyStore.getDefaultType()); } catch (KeyStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } InputStream keystoreInput = null; try { keystoreInput = new FileInputStream(m_keystorePath); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { keystore.load(keystoreInput, m_keystorePassword.toCharArray()); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (CertificateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { if (logger.isDebugEnabled()) { logger.debug("Keystore has " + keystore.size() + " keys"); } } catch (KeyStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } KeyStore truststore = null; try { truststore = KeyStore.getInstance(KeyStore.getDefaultType()); } catch (KeyStoreException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } InputStream truststoreInput = null; try { truststoreInput = new FileInputStream(m_truststorePath); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { truststore.load(truststoreInput, m_truststorePassword.toCharArray()); } catch (NoSuchAlgorithmException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (CertificateException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } SchemeRegistry schemeRegistry = new SchemeRegistry(); SSLSocketFactory schemeSocketFactory = null; try { schemeSocketFactory = new SSLSocketFactory(keystore, m_keystorePassword, truststore); } catch (KeyManagementException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnrecoverableKeyException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (KeyStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } schemeRegistry.register(new Scheme(m_protocol, m_port, schemeSocketFactory)); final HttpParams httpParams = new BasicHttpParams(); DefaultHttpClient httpClient = new DefaultHttpClient(new BasicClientConnectionManager(schemeRegistry), httpParams); /* Prepare the request to send */ Map<String, Object> responseMap = new HashMap<String, Object>(); HttpEntity request = new StringEntity(output, ContentType.TEXT_XML); //Create POST method HttpPost postMethod = new HttpPost(destURL); postMethod.setHeader("User-Agent", "EMC RID System"); postMethod.setHeader("Content-Type", "text/xml"); postMethod.setEntity(request); /* POST the request and process the response */ HttpResponse httpResponse = null; int code; try { httpResponse = httpClient.execute(postMethod); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (httpResponse.getEntity() != null) { code = httpResponse.getStatusLine().getStatusCode(); try { InputStream xml = httpResponse.getEntity().getContent(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(xml); docid = doc.getElementsByTagName("iodef:IncidentID").item(0).getTextContent(); System.out.println("ID of the newly created document " + docid); } catch (ParseException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } responseMap.put("success", true); responseMap.put("statusCode", code); } else { responseMap.put("success", false); responseMap.put("errorMessage", "Send failed (fill in exception)"); } return docid; }
From source file:com.wso2.mobile.mdm.utils.ServerUtilities.java
public static HttpClient getCertifiedHttpClient(Context context) { try {/* ww w .j av a 2 s .com*/ KeyStore localTrustStore = KeyStore.getInstance("BKS"); InputStream in = context.getResources().openRawResource(R.raw.emm_truststore); localTrustStore.load(in, CommonUtilities.TRUSTSTORE_PASSWORD.toCharArray()); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); SSLSocketFactory sslSocketFactory = new SSLSocketFactory(localTrustStore); schemeRegistry.register(new Scheme("https", sslSocketFactory, 443)); HttpParams params = new BasicHttpParams(); ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry); HttpClient client = new DefaultHttpClient(cm, params); return client; } catch (Exception e) { e.printStackTrace(); return null; } }
From source file:com.jt.https.test.send.java
public static String PostTo(String content) { String responseMessage = null; String filePath = ""; if (!filePath.endsWith("/")) { filePath = filePath + "/"; }//from ww w . ja va 2s . c o m HttpClient httpclient = new DefaultHttpClient(); try { KeyStore keystore = KeyStore.getInstance("jks"); KeyStore trustStore = KeyStore.getInstance("jks"); FileInputStream keystoreInstream = new FileInputStream( new File("F:\\temp\\?\\lz\\\\bis-stg-sdb.jks")); FileInputStream trustStoreInstream = new FileInputStream( new File("F:\\temp\\?\\lz\\\\EXV_GROUP_BIS_IFRONT_JTLZX_100.jks")); //FileInputStream keystoreInstream = new FileInputStream(new File("F:\\temp\\?\\lz\\\\pingan2jiangtai_test.jks")); //FileInputStream trustStoreInstream = new FileInputStream(new File("F:\\temp\\?\\lz\\\\pingan2jiangtai_test_trust.jks")); try { keystore.load(keystoreInstream, "123456".toCharArray()); trustStore.load(trustStoreInstream, "paic1234".toCharArray()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (CertificateException e) { e.printStackTrace(); } finally { keystoreInstream.close(); trustStoreInstream.close(); } SSLSocketFactory socketFactory = new SSLSocketFactory(SSLSocketFactory.SSL, keystore, "123456", trustStore, null, new TrustStrategy() { public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); Scheme sch = new Scheme("https", 8107, socketFactory); httpclient.getConnectionManager().getSchemeRegistry().register(sch); HttpPost post = new HttpPost("https://222.68.184.181:8107"); StringEntity entity = new StringEntity(content, "text/html", "UTF-8"); post.setEntity(entity); HttpResponse res = httpclient.execute(post); HttpEntity resEntity = res.getEntity(); if (resEntity != null) { responseMessage = convertStreamToString(resEntity.getContent()); System.out.println("???" + content); System.out.println("?" + responseMessage); } } catch (KeyStoreException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnrecoverableKeyException e) { e.printStackTrace(); } finally { httpclient.getConnectionManager().shutdown(); } return responseMessage; }
From source file:net.i2p.util.I2PSSLSocketFactory.java
/** * Loads certs from//from w w w. j a v a 2s . c om * the ~/.i2p/certificates/ and $I2P/certificates/ directories. */ private static SSLSocketFactory initSSLContext(I2PAppContext context, boolean loadSystemCerts, String relativeCertPath) throws GeneralSecurityException { Log log = context.logManager().getLog(I2PSSLSocketFactory.class); KeyStore ks; if (loadSystemCerts) { ks = KeyStoreUtil.loadSystemKeyStore(); if (ks == null) throw new GeneralSecurityException("Key Store init error"); } else { try { ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(null, "".toCharArray()); } catch (IOException ioe) { throw new GeneralSecurityException("Key Store init error", ioe); } } File dir = new File(context.getConfigDir(), relativeCertPath); int adds = KeyStoreUtil.addCerts(dir, ks); int totalAdds = adds; if (adds > 0) { if (log.shouldLog(Log.INFO)) log.info("Loaded " + adds + " trusted certificates from " + dir.getAbsolutePath()); } File dir2 = new File(context.getBaseDir(), relativeCertPath); if (!dir.getAbsolutePath().equals(dir2.getAbsolutePath())) { adds = KeyStoreUtil.addCerts(dir2, ks); totalAdds += adds; if (adds > 0) { if (log.shouldLog(Log.INFO)) log.info("Loaded " + adds + " trusted certificates from " + dir.getAbsolutePath()); } } if (totalAdds > 0 || loadSystemCerts) { if (log.shouldLog(Log.INFO)) log.info("Loaded total of " + totalAdds + " new trusted certificates"); } else { String msg = "No trusted certificates loaded (looked in " + dir.getAbsolutePath() + (dir.getAbsolutePath().equals(dir2.getAbsolutePath()) ? "" : (" and " + dir2.getAbsolutePath())) + ", SSL connections will fail. " + "Copy the cert in " + relativeCertPath + " from the router to the directory."; // don't continue, since we didn't load the system keystore, we have nothing. throw new GeneralSecurityException(msg); } SSLContext sslc = SSLContext.getInstance("TLS"); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); sslc.init(null, tmf.getTrustManagers(), context.random()); return sslc.getSocketFactory(); }
From source file:org.soyatec.windowsazure.internal.util.ssl.SslUtil.java
/** * Return the file's absolute path name string * /*from www . j a va 2 s . co m*/ * @param x509Cert * @return Path name string * @throws Exception */ public static String importCertificate(String x509Cert) throws Exception { // CREATE A KEYSTORE OF TYPE "Java Key Store" KeyStore ks = KeyStore.getInstance("JKS"); /* * LOAD THE STORE The first time you're doing this (i.e. the keystore * does not yet exist - you're creating it), you HAVE to load the * keystore from a null source with null password. Before any methods * can be called on your keystore you HAVE to load it first. Loading it * from a null source and null password simply creates an empty * keystore. At a later time, when you want to verify the keystore or * get certificates (or whatever) you can load it from the file with * your password. */ ks.load(null, null); // GET THE FILE CONTAINING YOUR CERTIFICATE File x509 = new File(x509Cert); FileInputStream fis = new FileInputStream(x509); BufferedInputStream bis = new BufferedInputStream(fis); // I USE x.509 BECAUSE THAT'S WHAT keytool CREATES CertificateFactory cf = CertificateFactory.getInstance("X.509"); // NOTE: THIS IS java.security.cert.Certificate NOT // java.security.Certificate X509Certificate cert = (X509Certificate) cf.generateCertificate(bis); ks.setCertificateEntry(CERT_ALIAS, cert); // SAVE THE KEYSTORE TO A FILE /* * After this is saved, I believe you can just do setCertificateEntry to * add entries and then not call store. I believe it will update the * existing store you load it from and not just in memory. */ File storeFile = new File(x509.getParentFile().getAbsolutePath(), KEYSTORE); ks.store(new FileOutputStream(storeFile), KEYSTORE_PASS.toCharArray()); return storeFile.getAbsolutePath(); }
From source file:org.keycloak.testsuite.oauth.ClientAuthSignedJWTTest.java
private static KeyStore getKeystore(InputStream is, String storePassword, String format) throws Exception { KeyStore keyStore = format.equals("JKS") ? KeyStore.getInstance(format) : KeyStore.getInstance(format, "BC"); keyStore.load(is, storePassword.toCharArray()); return keyStore; }
From source file:org.kymjs.kjframe.http.httpclient.HttpRequestBuilder.java
private static KeyStore loadCertificates(Context context) throws IOException { try {//from www .j a va 2 s .co m final KeyStore localTrustStore = KeyStore.getInstance("BKS"); final InputStream in = context.getResources().openRawResource(R.raw.hc_keystore); try { localTrustStore.load(in, null); } finally { in.close(); } return localTrustStore; } catch (Exception e) { final IOException ioe = new IOException("Failed to load SSL certificates"); ioe.initCause(e); throw ioe; } }
From source file:com.gamesalutes.utils.EncryptUtils.java
/** * Creates an <code>SSLContext</code> that uses the specified trusted certificates. * /*from w ww . j av a 2 s. co m*/ * @param protocol the {@link TransportSecurityProtocol} to use for the context * @param trustedCerts certificates to import into the <code>SSLContext</code> or <code>null</code> * to accept all issuers * @param privateKey the client key to authenticate the client with the server * @return the created <code>SSLContext</code> * @throws Exception if error occurs during the process of creating the context */ public static SSLContext createSSLContext(TransportSecurityProtocol protocol, PrivateKey privateKey, java.security.cert.X509Certificate... trustedCerts) throws Exception { if (trustedCerts != null && trustedCerts.length == 0) throw new IllegalArgumentException("trustedCerts is empty"); X509TrustManager defaultManager = null; KeyManager[] keyManagers = null; KeyStore keyStore = null; if (privateKey != null || trustedCerts != null) { // create a new key store instance that will install the certificates // and/or the private keys keyStore = KeyStore.getInstance(JKS_TYPE); keyStore.load(null, null); } // import the certs if (trustedCerts != null) { // set up the key manager for the certificates javax.net.ssl.TrustManagerFactory trustFact = javax.net.ssl.TrustManagerFactory .getInstance(KEY_MANAGEMENT_ALG_SUN_X509); // install the certificates in the key store and give them a unique alias int imported = 0; for (java.security.cert.X509Certificate cert : trustedCerts) { if (cert != null) keyStore.setCertificateEntry("cert" + ++imported, cert); } if (imported == 0) throw new IllegalArgumentException("no non-null certs in trustedCerts"); // add the certs to the trust factory trustFact.init(keyStore); // get a default trust manager TrustManager[] tms = trustFact.getTrustManagers(); if (tms != null && tms.length >= 1) defaultManager = (X509TrustManager) tms[0]; } // import the private key if (privateKey != null) { keyStore.setKeyEntry("client", privateKey, null, null); KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(privateKey.getAlgorithm()); kmfactory.init(keyStore, null); keyManagers = kmfactory.getKeyManagers(); } //create the SSL context based on these parameters SSLContext sslContext = SSLContext.getInstance(protocol.toString()); // use a CertX509TrustManager since default one will still fail validation for // self-signed certs sslContext.init(keyManagers, new TrustManager[] { trustedCerts != null ? new CertX509TrustManager(defaultManager, trustedCerts) : new CertX509TrustManager() }, null); return sslContext; }
From source file:com.emc.cto.ridagent.rid.util.HTTPSender.java
public static Map<String, Object> httpSend(PipelineOutput output, String destURL) { /* Set up TLS mutual authentication */ KeyStore keystore = null; try {//from ww w .ja va 2s . c o m keystore = KeyStore.getInstance(KeyStore.getDefaultType()); } catch (KeyStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } InputStream keystoreInput = null; try { keystoreInput = new FileInputStream(m_keystorePath); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { keystore.load(keystoreInput, m_keystorePassword.toCharArray()); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (CertificateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { if (logger.isDebugEnabled()) { logger.debug("Keystore has " + keystore.size() + " keys"); } } catch (KeyStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } KeyStore truststore = null; try { truststore = KeyStore.getInstance(KeyStore.getDefaultType()); } catch (KeyStoreException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } InputStream truststoreInput = null; try { truststoreInput = new FileInputStream(m_truststorePath); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { truststore.load(truststoreInput, m_truststorePassword.toCharArray()); } catch (NoSuchAlgorithmException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (CertificateException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { if (logger.isDebugEnabled()) { logger.debug("Truststore has " + truststore.size() + " keys"); } } catch (KeyStoreException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } SchemeRegistry schemeRegistry = new SchemeRegistry(); SSLSocketFactory schemeSocketFactory = null; try { schemeSocketFactory = new SSLSocketFactory(keystore, m_keystorePassword, truststore); } catch (KeyManagementException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnrecoverableKeyException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (KeyStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } schemeRegistry.register(new Scheme(m_protocol, m_port, schemeSocketFactory)); final HttpParams httpParams = new BasicHttpParams(); DefaultHttpClient httpClient = new DefaultHttpClient(new BasicClientConnectionManager(schemeRegistry), httpParams); /* Prepare the request to send */ String body = null; Map<String, Object> responseMap = new HashMap<String, Object>(); List<com.emc.documentum.xml.xproc.io.Source> sources = output.getSources(output.getPrimaryOutputPort()); if (sources != null && !sources.isEmpty()) { // pipeline should only return a single value - we return the first as the output Node node = sources.get(0).getNode(); InputStream is = sources.get(0).getInputStream(); Reader rdr = sources.get(0).getReader(); //For now we implement node only since we assume content is in the node if (node != null) { if (logger.isDebugEnabled()) { logger.debug("Node has content"); } body = Utilities.nodeToString(node); } else if (is != null) { if (logger.isDebugEnabled()) { logger.debug("Input stream has content"); } } else if (rdr != null) { if (logger.isDebugEnabled()) { logger.debug("Reader has content"); } } } HttpEntity request = new StringEntity(body, ContentType.TEXT_XML); //Create POST method HttpPost postMethod = new HttpPost(destURL); postMethod.setHeader("User-Agent", "EMC RID System"); postMethod.setHeader("Content-Type", "text/xml"); postMethod.setEntity(request); /* POST the request and process the response */ HttpResponse httpResponse = null; int code; String responseBody = null; try { httpResponse = httpClient.execute(postMethod); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (httpResponse.getEntity() != null) { code = httpResponse.getStatusLine().getStatusCode(); try { responseBody = EntityUtils.toString(httpResponse.getEntity()); } catch (ParseException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } if (logger.isDebugEnabled()) { logger.debug("Response status code: " + code); logger.debug("Reponse body =" + responseBody); } responseMap.put("success", true); responseMap.put("statusCode", code); responseMap.put("responseBody", responseBody); } else { responseMap.put("success", false); responseMap.put("errorMessage", "Send failed (fill in exception)"); } return responseMap; }
From source file:com.haoqee.chatsdk.net.Utility.java
public static HttpClient getNewHttpClient(long timeout) { try {/*from w w w. j av a 2s . c o m*/ KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); SSLSocketFactory sf = new MySSLSocketFactory(trustStore); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); HttpParams params = new BasicHttpParams(); //HttpConnectionParams.setConnectionTimeout(params, 10000); //HttpConnectionParams.setSoTimeout(params, 10000); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); //HttpProtocolParams.setContentCharset(params, HTTP.); 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); // Set the default socket timeout (SO_TIMEOUT) // in // milliseconds which is the timeout for waiting for data. HttpConnectionParams.setConnectionTimeout(params, Utility.SET_CONNECTION_TIMEOUT); long soc_time = Utility.SET_SOCKET_TIMEOUT + timeout; HttpConnectionParams.setSoTimeout(params, (int) soc_time); HttpClient client = new DefaultHttpClient(ccm, params); return client; } catch (Exception e) { return new DefaultHttpClient(); } }