List of usage examples for javax.net.ssl SSLSocket setSoTimeout
public synchronized void setSoTimeout(int timeout) throws SocketException
From source file:net.sf.jsignpdf.InstallCert.java
/** * The main - whole logic of Install Cert Tool. * /*from w ww . j ava 2 s .c o 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:com.tc.simple.apn.quicktests.Test.java
/** * @param args//from www. j a v a 2 s . c o m */ 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); try {/*from ww w .j a v a2s . c om*/ 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);//from w w w. j av a 2s . c om 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:org.wso2.carbon.databridge.agent.endpoint.binary.BinarySecureClientPoolFactory.java
@Override public Object createClient(String protocol, String hostName, int port) throws DataEndpointException, DataEndpointSecurityException, DataEndpointAgentConfigurationException { if (protocol.equalsIgnoreCase(DataEndpointConfiguration.Protocol.SSL.toString())) { int timeout = AgentHolder.getInstance() .getDataEndpointAgent(DataEndpointConstants.BINARY_DATA_AGENT_TYPE).getAgentConfiguration() .getSocketTimeoutMS();/*w w w . j av a 2 s. co m*/ String sslProtocols = AgentHolder.getInstance() .getDataEndpointAgent(DataEndpointConstants.BINARY_DATA_AGENT_TYPE).getAgentConfiguration() .getSslEnabledProtocols(); String ciphers = AgentHolder.getInstance() .getDataEndpointAgent(DataEndpointConstants.BINARY_DATA_AGENT_TYPE).getAgentConfiguration() .getCiphers(); try { SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault(); SSLSocket sslSocket = (SSLSocket) sslsocketfactory.createSocket(hostName, port); sslSocket.setSoTimeout(timeout); if (sslProtocols != null && sslProtocols.length() != 0) { String[] sslProtocolsArray = sslProtocols.split(","); sslSocket.setEnabledProtocols(sslProtocolsArray); } if (ciphers != null && ciphers.length() != 0) { String[] ciphersArray = ciphers.split(","); sslSocket.setEnabledCipherSuites(ciphersArray); } else { sslSocket.setEnabledCipherSuites(sslSocket.getSupportedCipherSuites()); } return sslSocket; } catch (IOException e) { throw new DataEndpointException( "Error while opening socket to " + hostName + ":" + port + ". " + e.getMessage(), e); } } else { throw new DataEndpointException("Unsupported protocol: " + protocol + ". Currently only " + DataEndpointConfiguration.Protocol.SSL.toString() + " supported."); } }
From source file:com.vmware.bdd.security.tls.SimpleSeverTrustTlsSocketFactory.java
/** * Wrap a socket to enable custom configuration(ciphers and protocols) to be * supported for the connection//from ww w .j av a 2 s . c o m * * @param sock a socket created by the * {@link SSLSocketFactory#createSocket() method} * @return a wrapped socket which has the client specified configuration */ private Socket wrapSocket(Socket sock) { SSLSocket sslSock = (SSLSocket) sock; sslSock.setSSLParameters(sslParams); try { sslSock.setSoTimeout(30000); } catch (SocketException e) { // } return sslSock; }
From source file:org.apache.tomcat.util.net.jsse.JSSE14Support.java
/** * JSSE in JDK 1.4 has an issue/feature that requires us to do a * read() to get the client-cert. As suggested by Andreas * Sterbenz// w w w.j ava2 s .co m */ private void synchronousHandshake(SSLSocket socket) throws IOException { InputStream in = socket.getInputStream(); int oldTimeout = socket.getSoTimeout(); socket.setSoTimeout(1000); byte[] b = new byte[0]; listener.reset(); socket.startHandshake(); int maxTries = 60; // 60 * 1000 = example 1 minute time out for (int i = 0; i < maxTries; i++) { if (logger.isTraceEnabled()) logger.trace("Reading for try #" + i); try { int x = in.read(b); } catch (SSLException sslex) { logger.info("SSL Error getting client Certs", sslex); throw sslex; } catch (IOException e) { // ignore - presumably the timeout } if (listener.completed) { break; } } socket.setSoTimeout(oldTimeout); if (listener.completed == false) { throw new SocketException("SSL Cert handshake timeout"); } }
From source file:com.hp.mercury.ci.jenkins.plugins.oo.ssl.FakeSocketFactory.java
@Override public Socket connectSocket(Socket sock, InetSocketAddress remoteAddress, InetSocketAddress localAddress, HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException { int connTimeout = HttpConnectionParams.getConnectionTimeout(params); int soTimeout = HttpConnectionParams.getSoTimeout(params); SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket(params)); if (localAddress != null) { // we need to bind explicitly sslsock.bind(localAddress);//from w ww .ja va 2 s . c om } sslsock.connect(remoteAddress, connTimeout); sslsock.setSoTimeout(soTimeout); return sslsock; }
From source file:net.lightbody.bmp.proxy.jetty.http.JsseListener.java
/** * @param p_serverSocket// ww w.j a v a 2 s . c o m * @return * @exception IOException */ protected Socket accept(ServerSocket p_serverSocket) throws IOException { try { SSLSocket s = (SSLSocket) p_serverSocket.accept(); if (getMaxIdleTimeMs() > 0) s.setSoTimeout(getMaxIdleTimeMs()); s.startHandshake(); // block until SSL handshaking is done return s; } catch (SSLException e) { log.warn(LogSupport.EXCEPTION, e); throw new IOException(e.getMessage()); } }
From source file:org.hyperic.hq.bizapp.agent.server.SSLConnectionListener.java
public AgentServerConnection getNewConnection() throws AgentConnectionException, InterruptedIOException { AgentServerConnection res;//from w w w . ja va 2s . com SSLSocket inConn = null; boolean success = false; try { inConn = (SSLSocket) this.listenSock.accept(); inConn.setSoTimeout(READ_TIMEOUT); } catch (InterruptedIOException exc) { throw exc; } catch (IOException exc) { throw new AgentConnectionException(exc.getMessage(), exc); } try { res = handleNewConn(inConn); success = true; } catch (SocketTimeoutException e) { InterruptedIOException toThrow = new InterruptedIOException(); toThrow.initCause(e); log.warn("socket timed out while handling a command from the server: " + e); log.debug(e, e); throw toThrow; } finally { if (!success) { close(inConn); } } return res; }