/** * Get the SSLSocketFactory for the current keystore and truststore specified in the connection * * @return The SSLSocketFactory constructed * @throws Exception */ protected SSLSocketFactory getSSLSocketFactory() throws Exception { KeyManager[] km = getKeyManagers(keyStoreFile, keyStorePassword); TrustManager[] tm = getTrustManagers(trustStoreFile, trustStorePassword); SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(km, tm, null); return sslContext.getSocketFactory(); }
public static String httsRequest(String url, String contentdata) { String str_return = ""; SSLContext sc = null; try { sc = SSLContext.getInstance("SSL"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } try { sc.init( null, new TrustManager[] {new TrustAnyTrustManager()}, new java.security.SecureRandom()); } catch (KeyManagementException e) { e.printStackTrace(); } URL console = null; try { console = new URL(url); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } HttpsURLConnection conn; try { conn = (HttpsURLConnection) console.openConnection(); conn.setRequestMethod("POST"); conn.setSSLSocketFactory(sc.getSocketFactory()); conn.setHostnameVerifier(new TrustAnyHostnameVerifier()); conn.setRequestProperty("Accept", "application/json"); conn.setDoInput(true); conn.setDoOutput(true); // contentdata="username=arcgis&password=arcgis123&client=requestip&f=json" String inpputs = contentdata; OutputStream os = conn.getOutputStream(); os.write(inpputs.getBytes()); os.close(); conn.connect(); InputStream is = conn.getInputStream(); // // DataInputStream indata = new DataInputStream(is); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String ret = ""; while (ret != null) { ret = reader.readLine(); if (ret != null && !ret.trim().equals("")) { str_return = str_return + ret; } } is.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return str_return; }
/** * Creates an "accept-all" SSLSocketFactory - ssl sockets will accept ANY certificate sent to them * - thus effectively just securing the communications. This could be set in a HttpsURLConnection * using HttpsURLConnection.setSSLSocketFactory(.....) * * @return SSLSocketFactory */ public static SSLSocketFactory createSSLSocketFactory() { SSLSocketFactory sslsocketfactory = null; TrustManager[] trustAllCerts = {new DummyTrustManager()}; try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); sslsocketfactory = sc.getSocketFactory(); } catch (Exception e) { e.printStackTrace(); } return sslsocketfactory; }
protected TrustAllSslSocketFactory() { TrustManager[] trustAllCerts = {new DummyTrustManager()}; SSLSocketFactory factory = null; try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new SecureRandom()); factory = sc.getSocketFactory(); } catch (Exception e) { e.printStackTrace(); } this.sslSocketFactory = factory; }
/* * Define the client side of the test. * * If the server prematurely exits, serverReady will be set to true * to avoid infinite hangs. */ void doClientSide() throws Exception { /* * Wait for server to get started. */ while (!serverReady) { Thread.sleep(50); } /* * See if an unknown keystore actually gets checked ok. */ System.out.println("=============="); System.out.println("Starting test0"); KeyStore uks = KeyStore.getInstance("JKS"); SSLContext ctx = SSLContext.getInstance("TLS"); KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); uks.load(new FileInputStream(unknownFilename), cpasswd); kmf.init(uks, cpasswd); TrustManager[] tms = new TrustManager[] {new MyJavaxX509TrustManager()}; ctx.init(kmf.getKeyManagers(), tms, null); SSLSocketFactory sslsf = (SSLSocketFactory) ctx.getSocketFactory(); System.out.println("Trying first socket " + serverPort); SSLSocket sslSocket = (SSLSocket) sslsf.createSocket("localhost", serverPort); doTest(sslSocket); /* * Now try the other way. */ com.sun.net.ssl.SSLContext ctx1 = com.sun.net.ssl.SSLContext.getInstance("TLS"); com.sun.net.ssl.KeyManagerFactory kmf1 = com.sun.net.ssl.KeyManagerFactory.getInstance("SunX509"); kmf1.init(uks, cpasswd); com.sun.net.ssl.TrustManager[] tms1 = new com.sun.net.ssl.TrustManager[] {new MyComX509TrustManager()}; ctx1.init(kmf1.getKeyManagers(), tms1, null); sslsf = (SSLSocketFactory) ctx1.getSocketFactory(); System.out.println("Trying second socket " + serverPort1); sslSocket = (SSLSocket) sslsf.createSocket("localhost", serverPort1); doTest(sslSocket); System.out.println("Completed test1"); }
/** Creates a new URL to use as the basis of a connection. */ public MsgRpcImpl( String username, String password, String host, int port, boolean ssl, boolean debugf) throws MalformedURLException { if (ssl) { // Install the all-trusting trust manager & HostnameVerifier try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init( null, new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted( java.security.cert.X509Certificate[] certs, String authType) {} public void checkServerTrusted( java.security.cert.X509Certificate[] certs, String authType) {} } }, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); HttpsURLConnection.setDefaultHostnameVerifier( new HostnameVerifier() { public boolean verify(String string, SSLSession ssls) { return true; } }); } catch (Exception e) { } u = new URL("https", host, port, "/api/1.0/"); } else { u = new URL("http", host, port, "/api/1.0/"); } /* login to msf server */ Object[] params = new Object[] {username, password}; Map results = exec("auth.login", params); /* save the temp token (lasts for 5 minutes of inactivity) */ rpcToken = results.get("token").toString(); /* generate a non-expiring token and use that */ params = new Object[] {rpcToken}; results = exec("auth.token_generate", params); rpcToken = results.get("token").toString(); }
public void run() { try { URL url = new URL(protocol + "://localhost:" + port + "/test1/" + f); HttpURLConnection urlc = (HttpURLConnection) url.openConnection(); if (urlc instanceof HttpsURLConnection) { HttpsURLConnection urlcs = (HttpsURLConnection) urlc; urlcs.setHostnameVerifier( new HostnameVerifier() { public boolean verify(String s, SSLSession s1) { return true; } }); urlcs.setSSLSocketFactory(ctx.getSocketFactory()); } byte[] buf = new byte[4096]; if (fixedLen) { urlc.setRequestProperty("XFixed", "yes"); } InputStream is = urlc.getInputStream(); File temp = File.createTempFile("Test1", null); temp.deleteOnExit(); OutputStream fout = new BufferedOutputStream(new FileOutputStream(temp)); int c, count = 0; while ((c = is.read(buf)) != -1) { count += c; fout.write(buf, 0, c); } is.close(); fout.close(); if (count != size) { throw new RuntimeException("wrong amount of data returned"); } String orig = root + "/" + f; compare(new File(orig), temp); temp.delete(); } catch (Exception e) { e.printStackTrace(); fail = true; } }
public static TcpSocket makeTls(TcpSocket upgrade) { try { SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, null, null); // get SSL factory because Java loves factories! SSLSocketFactory factory = sslContext.getSocketFactory(); // create new SSL socket SSLSocket socket; if (upgrade == null) { socket = (SSLSocket) factory.createSocket(); } // upgrade an existing socket else { socket = (SSLSocket) factory.createSocket( upgrade.peer.socket, upgrade.peer.socket.getInetAddress().getHostAddress(), upgrade.peer.socket.getPort(), false); socket.setUseClientMode(true); socket.startHandshake(); } // create the new TcpSocket instance TcpSocket self = new TcpSocket(); self.peer = new TcpSocketPeer(socket); // if upgrade, then initialize socket as already connected if (upgrade != null) self.peer.connected(self); return self; } catch (Exception e) { throw IOErr.make(e); } }
/** * Creates connection to the specified url. If the protocol is <code>https</code> the connection * created doesn't validate any certificates. * * @param url url to which connection has to be created * @param proxy proxy to be used. can be null * @return <code>URLConnection</code>. the connection is not yet connected * @throws IOException if an I/O exception occurs */ public static URLConnection createUnCertifiedConnection(URL url, Proxy proxy) throws IOException { if (sc == null) { try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, SSLUtil.DUMMY_TRUST_MANAGERS, new SecureRandom()); URLUtil.sc = sc; } catch (Exception ex) { throw new ImpossibleException(ex); } } URLConnection con = proxy == null ? url.openConnection() : url.openConnection(proxy); if ("https".equals(url.getProtocol())) { HttpsURLConnection httpsCon = (HttpsURLConnection) con; httpsCon.setSSLSocketFactory(sc.getSocketFactory()); httpsCon.setHostnameVerifier( new HostnameVerifier() { public boolean verify(String urlHostName, SSLSession session) { return true; } }); } return con; }