List of usage examples for javax.net.ssl SSLSocket close
public synchronized void close() throws IOException
From source file:Main.java
public static void main(String[] argv) throws Exception { int port = 443; String hostname = "hostname"; SSLSocketFactory factory = HttpsURLConnection.getDefaultSSLSocketFactory(); SSLSocket socket = (SSLSocket) factory.createSocket(hostname, port); socket.startHandshake();//from w ww. ja va 2s .co m // Retrieve the server's certificate chain Certificate[] serverCerts = socket.getSession().getPeerCertificates(); socket.close(); }
From source file:SecureClient.java
public static void main(String[] args) throws Exception { String host = "127.0.0.1"; SocketFactory sf = SSLSocketFactory.getDefault(); SSLSocket sock = (SSLSocket) sf.createSocket(host, PORT); System.out.println("Server connected"); InputStream rawIn = sock.getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(rawIn)); System.out.println(in.readLine()); sock.close(); }
From source file:net.sf.jsignpdf.InstallCert.java
/** * The main - whole logic of Install Cert Tool. * /* w w w . j a v a2 s . co m*/ * @param args * @throws Exception */ public static void main(String[] args) { String host; int port; char[] passphrase; System.out.println("InstallCert - Install CA certificate to Java Keystore"); System.out.println("====================================================="); final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); try { if ((args.length == 1) || (args.length == 2)) { String[] c = args[0].split(":"); host = c[0]; port = (c.length == 1) ? 443 : Integer.parseInt(c[1]); String p = (args.length == 1) ? "changeit" : args[1]; passphrase = p.toCharArray(); } else { String tmpStr; do { System.out.print("Enter hostname or IP address: "); tmpStr = StringUtils.defaultIfEmpty(reader.readLine(), null); } while (tmpStr == null); host = tmpStr; System.out.print("Enter port number [443]: "); tmpStr = StringUtils.defaultIfEmpty(reader.readLine(), null); port = tmpStr == null ? 443 : Integer.parseInt(tmpStr); System.out.print("Enter keystore password [changeit]: "); tmpStr = reader.readLine(); String p = "".equals(tmpStr) ? "changeit" : tmpStr; passphrase = p.toCharArray(); } char SEP = File.separatorChar; final File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security"); final File file = new File(dir, "cacerts"); System.out.println("Loading KeyStore " + file + "..."); InputStream in = new FileInputStream(file); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(in, passphrase); in.close(); SSLContext context = SSLContext.getInstance("TLS"); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0]; SavingTrustManager tm = new SavingTrustManager(defaultTrustManager); context.init(null, new TrustManager[] { tm }, null); SSLSocketFactory factory = context.getSocketFactory(); System.out.println("Opening connection to " + host + ":" + port + "..."); SSLSocket socket = (SSLSocket) factory.createSocket(host, port); socket.setSoTimeout(10000); try { System.out.println("Starting SSL handshake..."); socket.startHandshake(); socket.close(); System.out.println(); System.out.println("No errors, certificate is already trusted"); } catch (SSLException e) { System.out.println(); System.out.println("Certificate is not yet trusted."); // e.printStackTrace(System.out); } X509Certificate[] chain = tm.chain; if (chain == null) { System.out.println("Could not obtain server certificate chain"); return; } System.out.println(); System.out.println("Server sent " + chain.length + " certificate(s):"); System.out.println(); MessageDigest sha1 = MessageDigest.getInstance("SHA1"); MessageDigest md5 = MessageDigest.getInstance("MD5"); for (int i = 0; i < chain.length; i++) { X509Certificate cert = chain[i]; System.out.println(" " + (i + 1) + " Subject " + cert.getSubjectDN()); System.out.println(" Issuer " + cert.getIssuerDN()); sha1.update(cert.getEncoded()); System.out.println(" sha1 " + toHexString(sha1.digest())); md5.update(cert.getEncoded()); System.out.println(" md5 " + toHexString(md5.digest())); System.out.println(); } System.out.print("Enter certificate to add to trusted keystore or 'q' to quit [1]: "); String line = reader.readLine().trim(); int k = -1; try { k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1; } catch (NumberFormatException e) { } if (k < 0 || k >= chain.length) { System.out.println("KeyStore not changed"); } else { try { System.out.println("Creating keystore backup"); final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); final File backupFile = new File(dir, CACERTS_KEYSTORE + "." + dateFormat.format(new java.util.Date())); final FileInputStream fis = new FileInputStream(file); final FileOutputStream fos = new FileOutputStream(backupFile); IOUtils.copy(fis, fos); fis.close(); fos.close(); } catch (Exception e) { e.printStackTrace(); } System.out.println("Installing certificate..."); X509Certificate cert = chain[k]; String alias = host + "-" + (k + 1); ks.setCertificateEntry(alias, cert); OutputStream out = new FileOutputStream(file); ks.store(out, passphrase); out.close(); System.out.println(); System.out.println(cert); System.out.println(); System.out.println("Added certificate to keystore '" + file + "' using alias '" + alias + "'"); } } catch (Exception e) { System.out.println(); System.out.println("----------------------------------------------"); System.out.println("Problem occured during installing certificate:"); e.printStackTrace(); System.out.println("----------------------------------------------"); } System.out.println("Press Enter to finish..."); try { reader.readLine(); } catch (IOException e) { e.printStackTrace(); } }
From source file:MainClass.java
public static void main(String[] args) throws Exception { SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault(); String hostName = "hostName"; String fileName = "fileName"; SSLSocket sslsock = (SSLSocket) factory.createSocket(hostName, 443); SSLSession session = sslsock.getSession(); X509Certificate cert;/* ww w . j a v a 2 s. com*/ try { cert = (X509Certificate) session.getPeerCertificates()[0]; } catch (SSLPeerUnverifiedException e) { System.err.println(session.getPeerHost() + " did not present a valid certificate."); return; } System.out.println(session.getPeerHost() + " has presented a certificate belonging to:"); Principal p = cert.getSubjectDN(); System.out.println("\t[" + p.getName() + "]"); System.out.println("The certificate bears the valid signature of:"); System.out.println("\t[" + cert.getIssuerDN().getName() + "]"); System.out.print("Do you trust this certificate (y/n)? "); System.out.flush(); BufferedReader console = new BufferedReader(new InputStreamReader(System.in)); if (Character.toLowerCase(console.readLine().charAt(0)) != 'y') return; PrintWriter out = new PrintWriter(sslsock.getOutputStream()); out.print("GET " + fileName + " HTTP/1.0\r\n\r\n"); out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(sslsock.getInputStream())); String line; while ((line = in.readLine()) != null) System.out.println(line); sslsock.close(); }
From source file:com.tc.simple.apn.quicktests.Test.java
/** * @param args//from w ww .j av a2s.com */ public static void main(String[] args) { SSLSocket socket = null; try { String host = "gateway.sandbox.push.apple.com"; int port = 2195; String token = "de7f197546e41a76684f8e2d89f397ed165298d7772f4bd9b0f39c674b185b0f"; System.out.println(token.toCharArray().length); //String token = "8cebc7c08f79fa62f0994eb4298387ff930857ff8d14a50de431559cf476b223"; KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load(Test.class.getResourceAsStream("egram-dev-apn.p12"), "xxxxxxxxx".toCharArray()); KeyManagerFactory keyMgrFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyMgrFactory.init(keyStore, "xxxxxxxxx".toCharArray()); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyMgrFactory.getKeyManagers(), null, null); SSLSocketFactory socketFactory = sslContext.getSocketFactory(); socket = (SSLSocket) socketFactory.createSocket(host, port); String[] cipherSuites = socket.getSupportedCipherSuites(); socket.setEnabledCipherSuites(cipherSuites); socket.startHandshake(); char[] t = token.toCharArray(); byte[] b = Hex.decodeHex(t); OutputStream outputstream = socket.getOutputStream(); String payload = "{\"aps\":{\"alert\":\"yabadabadooo\"}}"; int expiry = (int) ((System.currentTimeMillis() / 1000L) + 7200); ByteArrayOutputStream bout = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bout); //command dos.writeByte(1); //id dos.writeInt(900); //expiry dos.writeInt(expiry); //token length. dos.writeShort(b.length); //token dos.write(b); //payload length dos.writeShort(payload.length()); //payload. dos.write(payload.getBytes()); byte[] byteMe = bout.toByteArray(); socket.getOutputStream().write(byteMe); socket.setSoTimeout(900); InputStream in = socket.getInputStream(); System.out.println(APNErrors.getError(in.read())); in.close(); outputstream.close(); } catch (Exception e) { e.printStackTrace(); } finally { try { socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
From source file:eu.eubrazilcc.lvl.core.http.client.TrustedHttpsClient.java
private static final void importCertificate(final String url, final KeyStore trustStore) throws Exception { final URL url2 = new URL(url); final SSLContext sslContext = SSLContext.getInstance("TLS"); final TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(trustStore); final X509TrustManager defaultTrustManager = (X509TrustManager) trustManagerFactory.getTrustManagers()[0]; final SavingTrustManager trustManager = new SavingTrustManager(defaultTrustManager); sslContext.init(null, new TrustManager[] { trustManager }, null); final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); final SSLSocket socket = (SSLSocket) sslSocketFactory.createSocket(url2.getHost(), url2.getPort() > 0 ? url2.getPort() : 443); socket.setSoTimeout(10000);/*from w w w. j a v a2 s .co m*/ try { socket.startHandshake(); socket.close(); } catch (SSLException e) { } final X509Certificate[] chain = trustManager.chain; if (chain == null) { LOGGER.error("Could not obtain server certificate chain from: " + url); return; } final MessageDigest sha1 = MessageDigest.getInstance("SHA1"); final MessageDigest md5 = MessageDigest.getInstance("MD5"); for (int i = 0; i < chain.length; i++) { final X509Certificate cert = chain[i]; final String alias = url2.getHost() + "-" + (i + 1); if (!trustStore.containsAlias(alias)) { sha1.update(cert.getEncoded()); md5.update(cert.getEncoded()); LOGGER.trace("Importing certificate to trusted keystore >> " + "Subject: " + cert.getSubjectDN() + ", Issuer: " + cert.getIssuerDN() + ", SHA1: " + printHexBinary(sha1.digest()) + ", MD5: " + printHexBinary(md5.digest()) + ", Alias: " + alias); trustStore.setCertificateEntry(alias, cert); } } }
From source file:com.zacwolf.commons.crypto._CRYPTOfactory.java
public static KeyStore addSiteTrustChain(final String sitehostname, final int httpsport, final KeyStore keystore, final char[] passphrase) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, KeyManagementException { final SSLContext context = SSLContext.getInstance("TLS"); final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(keystore);/* ww w . j av a2s.c o m*/ final X509TrustManager dtm = (X509TrustManager) tmf.getTrustManagers()[0]; final MyTrustManager tm = new MyTrustManager(dtm); context.init(null, new TrustManager[] { tm }, null); final SSLSocketFactory factory = context.getSocketFactory(); final SSLSocket socket = (SSLSocket) factory.createSocket(sitehostname, httpsport); socket.setSoTimeout(10000); try { System.out.println("Starting SSL handshake..."); socket.startHandshake(); socket.close(); System.out.println("Certificate for server " + sitehostname + " is already trusted"); } catch (SSLException e) { final X509Certificate[] chain = tm.chain; if (chain == null) { System.err.println("Could not obtain server certificate chain"); return keystore; } System.out.println("Server sent " + chain.length + " certificate(s):"); for (int i = 0; i < chain.length; i++) { final X509Certificate cert = chain[i]; MessageDigest.getInstance("SHA1").update(cert.getEncoded()); MessageDigest.getInstance("MD5").update(cert.getEncoded()); final String alias = sitehostname + "-" + (i + 1); keystore.setCertificateEntry(alias, cert); System.out.println("Added certificate to keystore using alias '" + alias + "'"); } } return keystore; }
From source file:Messenger.TorLib.java
public static void postToURL(String hostname, int port, String postKey, String data) throws IOException { Socket socket = TorSocket(hostname, port); SSLSocketFactory sslSf = (SSLSocketFactory) SSLSocketFactory.getDefault(); SSLSocket sslSocket = (SSLSocket) sslSf.createSocket(socket, null, socket.getPort(), false); sslSocket.setUseClientMode(true);// www.j a va 2 s . c o m sslSocket.startHandshake(); String path = "/" + postKey; BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(sslSocket.getOutputStream(), "UTF8")); wr.write("POST " + path + " HTTP/1.0\r\n"); wr.write("Content-Length: " + data.length() + "\r\n"); wr.write("Content-Type: application/x-www-form-urlencoded\r\n"); wr.write("\r\n"); wr.write(data); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(sslSocket.getInputStream())); String line; while ((line = rd.readLine()) != null) { System.out.println(line); } wr.close(); rd.close(); sslSocket.close(); }
From source file:org.hyperic.hq.bizapp.agent.server.SSLConnectionListener.java
private void close(SSLSocket socket) { if (socket != null) { try {//from w w w . ja va2 s . c om socket.close(); } catch (IOException exc) { log.debug(exc, exc); } } }
From source file:Messenger.TorLib.java
/** * This method makes a http GET request for the specified resource to the specified hostname. * It uses the SOCKS proxy to a connection over Tor. * The DNS lookup is also done over Tor. * This method only uses port 443 for SSL. * * @param hostname hostname for target server. * @param port port to connect to./*from ww w . j a v a2s. c om*/ * @param resource resource to lookup with GET request. * @return returns a JSON object. * @throws IOException * @throws JSONException */ public static JSONObject getJSON(String hostname, int port, String resource) throws IOException, JSONException, HttpException { //Create a SSL socket using Tor Socket socket = TorSocket(hostname, port); SSLSocketFactory sslSf = (SSLSocketFactory) SSLSocketFactory.getDefault(); SSLSocket sslSocket = (SSLSocket) sslSf.createSocket(socket, null, socket.getPort(), false); sslSocket.setUseClientMode(true); sslSocket.startHandshake(); openSockets.add(sslSocket); //Create the HTTP GET request and push it over the outputstream BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(sslSocket.getOutputStream(), "UTF8")); wr.write("GET /" + resource + " HTTP/1.0\r\n"); wr.write("Host: " + hostname + "\r\n"); wr.write("\r\n"); wr.flush(); //Listen for a response on the inputstream BufferedReader br = new BufferedReader(new InputStreamReader(sslSocket.getInputStream())); String t; boolean start = false; String output = ""; while ((t = br.readLine()) != null) { if (t.equals("")) { start = true; } if (start) { output = output + t; } } br.close(); wr.close(); sslSocket.close(); System.out.println(output); openSockets.remove(sslSocket); return new JSONObject(output); }