List of usage examples for javax.net.ssl SSLSocket close
public synchronized void close() throws IOException
From source file:LoginClient.java
private void runServer() { while (true) { try {// ww w.ja v a 2 s. c o m System.err.println("Waiting for connection..."); SSLSocket socket = (SSLSocket) serverSocket.accept(); BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter output = new PrintWriter(new OutputStreamWriter(socket.getOutputStream())); String userName = input.readLine(); String password = input.readLine(); if (userName.equals(CORRECT_USER_NAME) && password.equals(CORRECT_PASSWORD)) { output.println("Welcome, " + userName); } else { output.println("Login Failed."); } output.close(); input.close(); socket.close(); } catch (IOException ioException) { ioException.printStackTrace(); } } }
From source file:android.net.http.CertificateChainValidator.java
private void closeSocketThrowException(SSLSocket socket, String errorMessage) throws SSLHandshakeException, IOException { if (HttpLog.LOGV) { HttpLog.v("validation error: " + errorMessage); }/* w w w . j a v a 2s .com*/ if (socket != null) { SSLSession session = socket.getSession(); if (session != null) { session.invalidate(); } socket.close(); } throw new SSLHandshakeException(errorMessage); }
From source file:eu.nullbyte.android.urllib.CertPinningSSLSocketFactory.java
/** * @see org.apache.http.conn.scheme.SocketFactory#connectSocket(java.net.Socket, * String, int, java.net.InetAddress, int, * org.apache.http.params.HttpParams) *///from w w w. j a v a 2 s . c o m @Override public Socket connectSocket(Socket sock, String host, int port, InetAddress localAddress, int localPort, HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException { //Log.v(TAG, "connectSocket(socket: " + sock + ", host: " + host + ", port: " + port + ", localAddress: " + localAddress + ", localPort: " + localPort + ", params: " + params); int connTimeout = HttpConnectionParams.getConnectionTimeout(params); int soTimeout = HttpConnectionParams.getSoTimeout(params); InetSocketAddress remoteAddress = new InetSocketAddress(host, port); SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket()); if ((localAddress != null) || (localPort > 0)) { // we need to bind explicitly if (localPort < 0) { localPort = 0; // indicates "any" } InetSocketAddress isa = new InetSocketAddress(localAddress, localPort); sslsock.bind(isa); } sslsock.connect(remoteAddress, connTimeout); sslsock.setSoTimeout(soTimeout); try { getHostnameVerifier().verify(host, sslsock); // verifyHostName() didn't blowup - good! } catch (IOException iox) { // close the socket before re-throwing the exception try { sslsock.close(); } catch (Exception x) { /*ignore*/ } throw iox; } return sslsock; }
From source file:com.alphabetbloc.accessmrs.utilities.MySSLSocketFactory.java
@Override public Socket connectSocket(Socket sock, String host, int port, InetAddress localAddress, int localPort, HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException { if (host == null) { throw new IllegalArgumentException("Target host may not be null."); }//ww w. ja v a 2 s.c om if (params == null) { throw new IllegalArgumentException("Parameters may not be null."); } if (App.DEBUG) Log.e(TAG + "delete", "ConnectSocket with " + "\n\t host=" + host + "\n\t port=" + port + "\n\t localport=" + localPort); SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket()); if ((localAddress != null) || (localPort > 0)) { if (localPort < 0) localPort = 0; InetSocketAddress isa = new InetSocketAddress(localAddress, localPort); sslsock.bind(isa); } int connTimeout = HttpConnectionParams.getConnectionTimeout(params); int soTimeout = HttpConnectionParams.getSoTimeout(params); InetSocketAddress remoteAddress = new InetSocketAddress(host, port); sslsock.connect(remoteAddress, connTimeout); sslsock.setSoTimeout(soTimeout); try { hostnameVerifier.verify(host, sslsock); } catch (IOException iox) { try { sslsock.close(); } catch (Exception x) { } throw iox; } return sslsock; }
From source file:org.thoughtcrime.ssl.pinning.PinningSSLSocketFactory.java
@Override public Socket connectSocket(final Socket sock, final String host, final int port, final InetAddress localAddress, int localPort, final HttpParams params) throws IOException { final SSLSocket sslSock = (SSLSocket) ((sock != null) ? sock : createSocket()); if ((localAddress != null) || (localPort > 0)) { if (localPort < 0) { localPort = 0;/*from w ww . ja va 2s . c o m*/ } sslSock.bind(new InetSocketAddress(localAddress, localPort)); } final int connTimeout = HttpConnectionParams.getConnectionTimeout(params); final int soTimeout = HttpConnectionParams.getSoTimeout(params); final InetSocketAddress remoteAddress = new InetSocketAddress(host, port); sslSock.connect(remoteAddress, connTimeout); sslSock.setSoTimeout(soTimeout); try { SSLSocketFactory.STRICT_HOSTNAME_VERIFIER.verify(host, sslSock); } catch (IOException iox) { try { sslSock.close(); } catch (Exception ignored) { } throw iox; } return sslSock; }
From source file:com.photon.phresco.framework.rest.api.util.FrameworkServiceUtil.java
public static List<CertificateInfo> getCertificate(String host, int port) throws PhrescoException { List<CertificateInfo> certificates = new ArrayList<CertificateInfo>(); CertificateInfo info;/*from w ww. ja v a2s .co m*/ try { KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); 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(); SSLSocket socket = (SSLSocket) factory.createSocket(host, port); socket.setSoTimeout(10000); try { socket.startHandshake(); socket.close(); } catch (SSLException e) { } X509Certificate[] chain = tm.chain; for (int i = 0; i < chain.length; i++) { X509Certificate x509Certificate = chain[i]; String subjectDN = x509Certificate.getSubjectDN().getName(); String[] split = subjectDN.split(","); info = new CertificateInfo(); info.setSubjectDN(subjectDN); info.setDisplayName(split[0]); info.setCertificate(x509Certificate); certificates.add(info); } } catch (Exception e) { throw new PhrescoException(e); } return certificates; }
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>/* w w w .j a va 2 s. c o 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:org.jasig.portal.security.provider.saml.PublicKeyVerifyingSSLSocketFactory.java
/** * This method makes a connection to the server by utilizing the base class * method, but it adds a validation of the server's public key if one was * supplied previously./*from w w w . j a v a 2s .co m*/ * * @see org.apache.http.conn.ssl.SSLSocketFactory#connectSocket(java.net.Socket, java.lang.String, int, java.net.InetAddress, int, org.apache.http.params.HttpParams) */ @Override public Socket connectSocket(final Socket sock, final String host, final int port, final InetAddress localAddress, int localPort, final HttpParams params) throws IOException { SSLSocket newSocket = (SSLSocket) super.connectSocket(sock, host, port, localAddress, localPort, params); if (publicKey != null) { logger.debug("Verifying SSL Socket to {}:{} against configured public key {}", new Object[] { host, port, publicKey }); SSLSession session = newSocket.getSession(); Certificate[] certs = session.getPeerCertificates(); boolean matchFound = false; for (int i = 0; i < certs.length; i++) { X509Certificate x509 = (X509Certificate) certs[i]; PublicKey certKey = x509.getPublicKey(); if (certKey.equals(publicKey)) { logger.debug("Validated public key against server key: {}", certKey); matchFound = true; break; } logger.debug("server key doesn't match public key: {} ", certKey); } if (!matchFound) { newSocket.close(); throw new IOException("Unable to verify the server's public key"); } } return newSocket; }
From source file:i2p.bote.imap.ImapService.java
public ImapService(Configuration configuration, final PasswordVerifier passwordVerifier, EmailFolderManager folderManager) throws ConfigurationException { this.folderManager = folderManager; setLog(LoggerFactory.getLogger(ImapService.class)); // Set up the keystore for the SSL certificate sslKeyStore = configuration.getSSLKeyStoreFile(); setFileSystem(new FileSystem() { @Override//from w w w.ja v a2 s.co m public InputStream getResource(String resource) throws IOException { return null; } @Override public File getFile(String fileURL) throws FileNotFoundException { if (fileURL.equals(SSL_KEYSTORE_FILE)) return sslKeyStore; return null; } @Override public File getBasedir() throws FileNotFoundException { return null; } }); HierarchicalConfiguration cfg = new HierarchicalConfiguration(); SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault(); SSLSocket s = null; try { // Create an unconnected socket for getting supported cipher suites s = (SSLSocket) sf.createSocket(); // enable STARTTLS using the above keystore cfg.setProperty("tls.[@startTLS]", true); cfg.setProperty("tls.keystore", SSL_KEYSTORE_FILE); cfg.setProperty("tls.secret", configuration.getSSLKeyStorePassword()); // select strong cipher suites cfg.setProperty("tls.supportedCipherSuites.cipherSuite", StrongTls.getRecommendedCipherSuites(s.getSupportedCipherSuites())); } catch (IOException e) { log.error("Couldn't determine supported cipher suites", e); } finally { if (s != null) try { s.close(); } catch (IOException e) { } } configure(cfg); // use the defaults for the rest setListenAddresses(new InetSocketAddress(configuration.getImapAddress(), configuration.getImapPort())); mailboxSessionMapperFactory = new MapperFactory(folderManager); MailboxACLResolver aclResolver = createMailboxACLResolver(); GroupMembershipResolver groupMembershipResolver = new GroupMembershipResolver() { public boolean isMember(String user, String group) { return true; } }; Authenticator authenticator = createAuthenticator(passwordVerifier); StoreMailboxManager<String> mailboxManager = new StoreMailboxManager<String>(mailboxSessionMapperFactory, authenticator, aclResolver, groupMembershipResolver); mailboxManager.setDelegatingMailboxListener(new HashMapDelegatingMailboxListener()); mailboxManager.setMailboxSessionIdGenerator(new RandomMailboxSessionIdGenerator()); SubscriptionManager subscriptionManager = createSubscriptionManager(); ImapProcessor processor = DefaultImapProcessorFactory.createDefaultProcessor(mailboxManager, subscriptionManager); setImapProcessor(processor); setImapEncoder(DefaultImapEncoderFactory.createDefaultEncoder(new Localizer() { public String localize(HumanReadableText text, Locales locales) { return text.getDefaultValue(); } }, true)); setImapDecoder(DefaultImapDecoderFactory.createDecoder()); }
From source file:android.core.SSLSocketTest.java
public void testSSLHandshakeHangTimeout() { Thread thread = new Thread() { @Override/*from w ww .ja va 2s . c om*/ public void run() { try { SSLSocket socket = (SSLSocket) clientFactory.createSocket("www.heise.de", 80); socket.setSoTimeout(5000); socket.startHandshake(); socket.close(); } catch (Exception ex) { handshakeException = ex; } } }; thread.start(); try { thread.join(10000); } catch (InterruptedException ex) { // Ignore. } if (handshakeException == null) { fail("SSL handshake should have failed."); } }