List of usage examples for javax.net.ssl SSLSocketFactory createSocket
@Override public Socket createSocket(InetAddress address, int port) throws IOException
From source file:gov.miamidade.open311.utilities.SslContextedSecureProtocolSocketFactory.java
/** * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int) *//*www. ja v a 2s . c om*/ public Socket createSocket(String host, int port) throws IOException, UnknownHostException { SSLSocketFactory sf = (SSLSocketFactory) getSslSocketFactory(); SSLSocket sslSocket = (SSLSocket) sf.createSocket(host, port); verifyHostname(sslSocket); return sslSocket; }
From source file:org.openhim.mediator.denormalization.ATNAAuditingActor.java
private Socket getSocket(final MediatorSocketRequest req) throws IOException { if (req.isSecure()) { SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault(); return factory.createSocket(req.getHost(), req.getPort()); } else {/*from w w w. ja va2s. com*/ return new Socket(req.getHost(), req.getPort()); } }
From source file:test.integ.be.fedict.commons.eid.client.SSLTest.java
@Test public void testTestEIDBelgiumBe() throws Exception { Security.addProvider(new BeIDProvider()); SSLContext sslContext = SSLContext.getInstance("TLS"); KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("BeID"); keyManagerFactory.init(null);// www . j a va 2 s . c o m SecureRandom secureRandom = new SecureRandom(); sslContext.init(keyManagerFactory.getKeyManagers(), new TrustManager[] { new ClientTestX509TrustManager() }, secureRandom); SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket("test.eid.belgium.be", 443); LOG.debug("socket created"); SSLSession sslSession = sslSocket.getSession(); Certificate[] peerCertificates = sslSession.getPeerCertificates(); for (Certificate peerCertificate : peerCertificates) { LOG.debug("peer certificate: " + ((X509Certificate) peerCertificate).getSubjectX500Principal()); } }
From source file:org.kuali.mobility.push.dao.PushDaoImpl.java
private SSLSocket openConnectionToAPNS(String host, int port, String key, String passphrase) { SSLSocket socket;/*from ww w . j a v a 2 s .c om*/ try { KeyStore keyStore = KeyStore.getInstance("PKCS12"); // keyStore.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("newcert.p12"), "strange word to use".toCharArray()); // keyStore.load(getClass().getResourceAsStream("/newcert.p12"), "strange word to use".toCharArray()); // keyStore.load(this.getClass().getClassLoader().getResourceAsStream("newcert.p12"), "strange word to use".toCharArray()); // This works when built with Eclipse, but not when built from command line. // Has to do with where the build system puts /resources/*.p12 file // keyStore.load(this.getClass().getClassLoader().getResourceAsStream(key), "strange word to use".toCharArray()); // Currently only works when read from the server's FS. Won't currently read from within eclipse project. // Putting it in /opt/kme/push prevents naming conflicts. keyStore.load(new FileInputStream("/opt/kme/push/newcert.p12"), "strange word to use".toCharArray()); KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("sunx509"); keyManagerFactory.init(keyStore, "strange word to use".toCharArray()); TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("sunx509"); trustManagerFactory.init(keyStore); SSLContext sslCtx = SSLContext.getInstance("TLS"); sslCtx.init(keyManagerFactory.getKeyManagers(), null, null); SSLSocketFactory sslSocketFactory = sslCtx.getSocketFactory(); socket = (SSLSocket) sslSocketFactory.createSocket(host, port); socket.startHandshake(); //Diagnostic output Enumeration e = keyStore.aliases(); LOG.info(e.toString()); while (e.hasMoreElements()) { LOG.info("Alias: " + e.nextElement().toString()); } String not = (socket.isConnected()) ? "" : "NOT "; LOG.info("SSLSocket is " + not + "Connected"); LOG.info("Connected to: " + socket.getInetAddress().getCanonicalHostName()); LOG.info("Connected to: " + socket.getInetAddress().getHostAddress()); String cs[] = socket.getEnabledCipherSuites(); LOG.info("CipherSuites: " + Arrays.toString(cs)); String ep[] = socket.getEnabledProtocols(); LOG.info("Enabled Protocols: " + Arrays.toString(ep)); LOG.info("Timeout: " + socket.getSoTimeout()); LOG.info("Send Buffer Size: " + socket.getSendBufferSize()); return socket; } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:IMAPService.java
public IMAPService(String _server, int _port) { File mailboxRootDir = new File(mailboxRootDirectory); mailboxRootDir.mkdir();/*from w ww . j ava 2 s . com*/ this.server = _server; this.port = _port; this.emailFolders = new ArrayList<EmailFolder>(); this.deleteAfterDownload = false; // TODO Auto-generated constructor stub try { SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault(); this.socket = (SSLSocket) sslSocketFactory.createSocket(this.server, this.port); this.reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); this.output = new PrintWriter(socket.getOutputStream()); System.out.println(parseServerResponse()); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.apache.abdera.protocol.client.util.ClientAuthSSLProtocolSocketFactory.java
public Socket createSocket(String host, int port, InetAddress chost, int cport, HttpConnectionParams params) throws IOException, UnknownHostException, ConnectTimeoutException { SSLContext context;/*from w w w . j a va 2 s.c o m*/ SSLSocketFactory factory = null; SSLSocket socket = null; try { KeyManagerFactory kmf; context = SSLContext.getInstance(protocol); kmf = KeyManagerFactory.getInstance(kmfFactory); TrustManager tm = (this.tm != null) ? this.tm : new NonOpTrustManager(); kmf.init(ks, keyStorePass.toCharArray()); context.init(kmf.getKeyManagers(), new TrustManager[] { tm }, null); factory = context.getSocketFactory(); socket = (SSLSocket) factory.createSocket(host, port); return socket; } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.gvnix.service.roo.addon.addon.security.SecurityServiceImpl.java
/** * Get certificates in the chain of the host server and import them. * <p>/*from w ww . ja v a 2s.co m*/ * Tries to get the certificates in the certificates chain of the host * server and import them to: * <ol> * <li>A custom keystore in <code>SRC_MAIN_RESOURCES/gvnix-cacerts</code></li> * <li>The JVM cacerts keystore in * <code>$JAVA_HOME/jre/lib/security/cacerts</code>. Here we can have a * problem if JVM <code>cacerts</code> file is not writable by the user due * to file permissions. In this case we throw an exception informing about * the error.</li> * </ol> * </p> * <p> * With that operation we can try again to get the WSDL.<br/> * Also it exports the chain certificates to <code>.cer</code> files in * <code>SRC_MAIN_RESOURCES</code>, so the developer can distribute them for * its installation in other environments or just in case we reach the * problem with the JVM <code>cacerts</code> file permissions. * </p> * * @see GvNix509TrustManager#saveCertFile(String, X509Certificate, * FileManager, PathResolver) * @see <a href= * "http://download.oracle.com/javase/6/docs/technotes/tools/solaris/keytool.html" * >Java SE keytool</a>. */ protected Document installCertificates(String loc, String pass) throws NoSuchAlgorithmException, KeyStoreException, Exception, KeyManagementException, MalformedURLException, IOException, UnknownHostException, SocketException, SAXException { // Create a SSL context SSLContext context = SSLContext.getInstance("TLS"); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); // Passphrase of the keystore: "changeit" by default char[] passArray = (StringUtils.isNotBlank(pass) ? pass.toCharArray() : "changeit".toCharArray()); // Get the project keystore and copy it from JVM if not exists File keystore = getProjectKeystore(); tmf.init(GvNix509TrustManager.loadKeyStore(keystore, passArray)); X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0]; GvNix509TrustManager tm = new GvNix509TrustManager(defaultTrustManager); context.init(null, new TrustManager[] { tm }, null); SSLSocketFactory factory = context.getSocketFactory(); // Open URL location (default 443 port if not defined) URL url = new URL(loc); String host = url.getHost(); int port = url.getPort() == -1 ? 443 : url.getPort(); SSLSocket socket = (SSLSocket) factory.createSocket(host, port); socket.setSoTimeout(10000); Document doc = null; try { socket.startHandshake(); URLConnection connection = url.openConnection(); if (connection instanceof HttpsURLConnection) { ((HttpsURLConnection) connection).setSSLSocketFactory(factory); } doc = XmlUtils.getDocumentBuilder().parse(connection.getInputStream()); socket.close(); } catch (SSLException ssle) { // Get needed certificates for this host getCerts(tm, host, keystore, passArray); doc = getWsdl(loc, pass); } catch (IOException ioe) { invalidHostCert(passArray, keystore, tm, host); } Validate.notNull(doc, "No valid document format"); return doc; }
From source file:com.isecpartners.gizmo.HttpRequest.java
public boolean fetchResponse(boolean cached) { this.cached = cached; OutputStream out = null;//from w ww. j a va 2 s. c o m BufferedReader strBr = null; try { if (cached) { strBr = new BufferedReader(new StringReader(this.interrimContents.toString())); } removeLine("PROXY-CONNECTION", workingContents); updateContentLength(); if (mk_header(workingContents).contains("CONNECT") && !this.connect_protocol_handled) { handle_connect_protocol(); if (!GizmoView.getView().config().terminateSSL()) { this.passthroughssl = true; return false; } } if (isSSL || this.sock instanceof SSLSocket) { SSLSocket sslSock = (SSLSocket) this.sock; SSLSocket sslOut = null; if (workingContents == null) { return false; } if (workingContents.indexOf("\r\n") == -1) { return false; } if (!this.override_host) host = rewriteMethodLine(workingContents); if (!user_defined_port) { port = 443; } if (outboundSock == null || (!(outboundSock instanceof SSLSocket))) { SSLSocketFactory sslsocketfactory = sloppySSL(); sslOut = (SSLSocket) sslsocketfactory.createSocket(host, port); } else { sslOut = (SSLSocket) outboundSock; } sslOut.getOutputStream().write(workingContents.toString().getBytes()); this.resp = HttpResponse.create(sslOut.getInputStream()); if (resp == null) { return false; } } else { //if (!this.override_host) host = rewriteMethodLine(workingContents); outboundSock = new Socket(host, port); outboundSock.getOutputStream().write(workingContents.toString().getBytes()); this.resp = HttpResponse.create(outboundSock.getInputStream()); if (resp == null) { return false; } } this.addContents(workingContents.toString()); this.header = workingContents.substring(0, this.workingContents.indexOf("\r\n")); this.url = getUrlPath(header); this.version = getVersion(this.header); } catch (SocketException e) { Logger.getLogger(HttpRequest.class.getName()).log(Level.SEVERE, null, e); return false; } catch (javax.net.ssl.SSLHandshakeException e) { try { GizmoView.getView().setStatus("couldn't connect with ssl.. cert issues?"); sock.close(); } catch (IOException ex) { Logger.getLogger(HttpRequest.class.getName()).log(Level.SEVERE, null, ex); } return false; } catch (IOException ex) { Logger.getLogger(HttpRequest.class.getName()).log(Level.SEVERE, null, ex); return false; } catch (FailedRequestException e) { GizmoView.getView().setStatus("malformed server response"); } catch (Exception e) { try { Logger.getLogger(HttpRequest.class.getName()).log(Level.SEVERE, null, e); GizmoView.getView().setStatus("couldn't connect"); this.sock.close(); return false; } catch (IOException ex) { Logger.getLogger(HttpRequest.class.getName()).log(Level.SEVERE, null, ex); } } this.wakeupAndSend(); resp.setRequest(this); return true; }
From source file:edu.uiuc.ncsa.myproxy.MyProxyLogon.java
/** * Connects to the MyProxy server at the desired host and port. Requires * host authentication via SSL. The host's certificate subject must * match the requested hostname. If CA certificates are found in the * standard GSI locations, they will be used to verify the server's * certificate. If trust roots are requested and no CA certificates are * found, the server's certificate will still be accepted. *//*from w w w . ja v a 2 s .c o m*/ public void connect() throws IOException, GeneralSecurityException { try { SSLContext sc = SSLContext.getInstance("SSL"); MyTrustManager mtm = new MyTrustManager(getMlf(), getExistingTrustRootPath(), getServerDN()); mtm.setHost(hostLookup()); TrustManager[] trustAllCerts = new TrustManager[] { mtm }; sc.init(getKeyManagers(), trustAllCerts, new java.security.SecureRandom()); SSLSocketFactory sf = sc.getSocketFactory(); this.socket = (SSLSocket) sf.createSocket(this.hostLookup(), this.port); if (0 < getSocketTimeout()) { // NOTE that this is an integer that is used for milliseconds. socket.setSoTimeout((int) getSocketTimeout()); } this.socket.startHandshake(); this.socketIn = new BufferedInputStream(this.socket.getInputStream()); this.socketOut = new BufferedOutputStream(this.socket.getOutputStream()); this.state = State.CONNECTED; } catch (Throwable t) { handleException(t, getClass().getSimpleName() + " could not connect to the server, socket " + (this.socket == null ? "" : "not") + " created."); } }
From source file:com.vmware.admiral.host.BaseManagementHostClusterIT.java
protected void waitWhilePortIsListening(ManagementHost host) throws TimeoutException, InterruptedException { SSLSocketFactory factory = ManagementHostAuthUsersTest.getUnsecuredSSLSocketFactory(); boolean portListening = true; while (portListening) { try (Socket s = factory.createSocket((String) null, host.getSecurePort())) { logger.log(Level.INFO, "Wait while port '" + host.getSecurePort() + "' is listening..."); } catch (Exception e) { portListening = false;//from ww w. j a v a2s. c o m } finally { Thread.sleep(2000); } } }