javax.net.ssl.SSLSocket Java Examples

The following examples show how to use javax.net.ssl.SSLSocket. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: EasySSLSocketFactory.java    From sana.mobile with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * @see org.apache.http.conn.scheme.SocketFactory#connectSocket(java.net.Socket,
 * java.lang.String, int, java.net.InetAddress, int,
 * org.apache.http.params.HttpParams)
 */
public Socket connectSocket(Socket sock, String host, int port,
                            InetAddress localAddress, int localPort, HttpParams params)
        throws IOException, UnknownHostException, ConnectTimeoutException {
    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);
    return sslsock;

}
 
Example #2
Source File: ConnectionSpec.java    From styT with Apache License 2.0 6 votes vote down vote up
/**
 * Returns {@code true} if the socket, as currently configured, supports this connection spec. In
 * order for a socket to be compatible the enabled cipher suites and protocols must intersect.
 *
 * <p>For cipher suites, at least one of the {@link #cipherSuites() required cipher suites} must
 * match the socket's enabled cipher suites. If there are no required cipher suites the socket
 * must have at least one cipher suite enabled.
 *
 * <p>For protocols, at least one of the {@link #tlsVersions() required protocols} must match the
 * socket's enabled protocols.
 */
public boolean isCompatible(SSLSocket socket) {
  if (!tls) {
    return false;
  }

  if (tlsVersions != null && !nonEmptyIntersection(
      Util.NATURAL_ORDER, tlsVersions, socket.getEnabledProtocols())) {
    return false;
  }

  if (cipherSuites != null && !nonEmptyIntersection(
      CipherSuite.ORDER_BY_NAME, cipherSuites, socket.getEnabledCipherSuites())) {
    return false;
  }

  return true;
}
 
Example #3
Source File: TrustManagerExt.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType,
    Socket socket) throws CertificateException {
  if (!option.isAuthPeer()) {
    return;
  }

  String ip = null;
  if (socket != null && socket.isConnected()
      && socket instanceof SSLSocket) {
    InetAddress inetAddress = socket.getInetAddress();
    if (inetAddress != null) {
      ip = inetAddress.getHostAddress();
    }
  }
  checkTrustedCustom(chain, ip);
  trustManager.checkClientTrusted(chain, authType, socket);
}
 
Example #4
Source File: SdkTlsSocketFactoryTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void noTLS() throws NoSuchAlgorithmException, IOException {
    SdkTlsSocketFactory f = new SdkTlsSocketFactory(SSLContext.getDefault(), null);
    try (SSLSocket socket = new TestSSLSocket() {
        @Override
        public String[] getSupportedProtocols() {
            return shuffle(new String[] {"SSLv2Hello", "SSLv3"});
        }

        @Override
        public String[] getEnabledProtocols() {
            return new String[] {"SSLv3"};
        }

        @Override
        public void setEnabledProtocols(String[] protocols) {
            // For backward compatibility
            assertTrue(Arrays.equals(protocols, new String[] {"SSLv3"}));
        }
    }) {
        f.prepareSocket(socket);
    }
}
 
Example #5
Source File: SSLSocketTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
public void test_SSLSocket_startHandshake_noClientCertificate() throws Exception {
    TestSSLContext c = TestSSLContext.create();
    SSLContext serverContext = c.serverContext;
    SSLContext clientContext = c.clientContext;
    SSLSocket client = (SSLSocket)
        clientContext.getSocketFactory().createSocket(c.host, c.port);
    final SSLSocket server = (SSLSocket) c.serverSocket.accept();
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Future<Void> future = executor.submit(new Callable<Void>() {
        @Override public Void call() throws Exception {
            server.startHandshake();
            return null;
        }
    });
    executor.shutdown();
    client.startHandshake();
    future.get();
    client.close();
    server.close();
    c.close();
}
 
Example #6
Source File: CloseSocket.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    try (Server server = new Server()) {
        new Thread(server).start();

        SocketFactory factory = SSLSocketFactory.getDefault();
        try (SSLSocket socket = (SSLSocket) factory.createSocket("localhost",
                server.getPort())) {
            socket.setSoTimeout(2000);
            System.out.println("Client established TCP connection");
            boolean failed = false;
            for (TestCase testCase : testCases) {
                try {
                    testCase.test(socket);
                    System.out.println("ERROR: no exception");
                    failed = true;
                } catch (IOException e) {
                    System.out.println("Failed as expected: " + e);
                }
            }
            if (failed) {
                throw new Exception("One or more tests failed");
            }
        }
    }
}
 
Example #7
Source File: CloseSocket.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    try (Server server = new Server()) {
        new Thread(server).start();

        SocketFactory factory = SSLSocketFactory.getDefault();
        try (SSLSocket socket = (SSLSocket) factory.createSocket("localhost",
                server.getPort())) {
            socket.setSoTimeout(2000);
            System.out.println("Client established TCP connection");
            boolean failed = false;
            for (TestCase testCase : testCases) {
                try {
                    testCase.test(socket);
                    System.out.println("ERROR: no exception");
                    failed = true;
                } catch (IOException e) {
                    System.out.println("Failed as expected: " + e);
                }
            }
            if (failed) {
                throw new Exception("One or more tests failed");
            }
        }
    }
}
 
Example #8
Source File: CertificateUtils.java    From nifi-registry with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the DN extracted from the peer certificate (the server DN if run on the client; the client DN (if available) if run on the server).
 *
 * If the client auth setting is WANT or NONE and a client certificate is not present, this method will return {@code null}.
 * If the client auth is NEED, it will throw a {@link CertificateException}.
 *
 * @param socket the SSL Socket
 * @return the extracted DN
 * @throws CertificateException if there is a problem parsing the certificate
 */
public static String extractPeerDNFromSSLSocket(Socket socket) throws CertificateException {
    String dn = null;
    if (socket instanceof SSLSocket) {
        final SSLSocket sslSocket = (SSLSocket) socket;

        boolean clientMode = sslSocket.getUseClientMode();
        logger.debug("SSL Socket in {} mode", clientMode ? "client" : "server");
        ClientAuth clientAuth = getClientAuthStatus(sslSocket);
        logger.debug("SSL Socket client auth status: {}", clientAuth);

        if (clientMode) {
            logger.debug("This socket is in client mode, so attempting to extract certificate from remote 'server' socket");
           dn = extractPeerDNFromServerSSLSocket(sslSocket);
        } else {
            logger.debug("This socket is in server mode, so attempting to extract certificate from remote 'client' socket");
           dn = extractPeerDNFromClientSSLSocket(sslSocket);
        }
    }

    return dn;
}
 
Example #9
Source File: HttpResponseCache.java    From wildfly-samples with MIT License 6 votes vote down vote up
public Entry(URI uri, RawHeaders varyHeaders, HttpURLConnection httpConnection)
    throws IOException {
  this.uri = uri.toString();
  this.varyHeaders = varyHeaders;
  this.requestMethod = httpConnection.getRequestMethod();
  this.responseHeaders = RawHeaders.fromMultimap(httpConnection.getHeaderFields(), true);

  SSLSocket sslSocket = getSslSocket(httpConnection);
  if (sslSocket != null) {
    cipherSuite = sslSocket.getSession().getCipherSuite();
    Certificate[] peerCertificatesNonFinal = null;
    try {
      peerCertificatesNonFinal = sslSocket.getSession().getPeerCertificates();
    } catch (SSLPeerUnverifiedException ignored) {
    }
    peerCertificates = peerCertificatesNonFinal;
    localCertificates = sslSocket.getSession().getLocalCertificates();
  } else {
    cipherSuite = null;
    peerCertificates = null;
    localCertificates = null;
  }
}
 
Example #10
Source File: CloseSocket.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    try (Server server = new Server()) {
        new Thread(server).start();

        SocketFactory factory = SSLSocketFactory.getDefault();
        try (SSLSocket socket = (SSLSocket) factory.createSocket("localhost",
                server.getPort())) {
            socket.setSoTimeout(2000);
            System.out.println("Client established TCP connection");
            boolean failed = false;
            for (TestCase testCase : testCases) {
                try {
                    testCase.test(socket);
                    System.out.println("ERROR: no exception");
                    failed = true;
                } catch (IOException e) {
                    System.out.println("Failed as expected: " + e);
                }
            }
            if (failed) {
                throw new Exception("One or more tests failed");
            }
        }
    }
}
 
Example #11
Source File: CipherTestUtils.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static void printInfo(SSLSocket socket) {
    System.out.println();
    System.out.println("--- SSL Socket Info ---");
    System.out.print(" SupportedProtocols    : ");
    printStringArray(socket.getSupportedProtocols());
    System.out.println(" EnabledProtocols      : "
            + socket.getEnabledProtocols()[0]);
    System.out.print(" SupportedCipherSuites : ");
    String[] supportedCipherSuites = socket.getEnabledCipherSuites();
    Arrays.sort(supportedCipherSuites);
    printStringArray(supportedCipherSuites);
    System.out.println(" EnabledCipherSuites   : "
            + socket.getEnabledCipherSuites()[0]);
    System.out.println(" NeedClientAuth        : "
            + socket.getNeedClientAuth());
    System.out.println(" WantClientAuth        : "
            + socket.getWantClientAuth());
    System.out.println("-----------------------");
}
 
Example #12
Source File: HttpResponseCache.java    From reader with MIT License 6 votes vote down vote up
public Entry(URI uri, RawHeaders varyHeaders, HttpURLConnection httpConnection)
    throws IOException {
  this.uri = uri.toString();
  this.varyHeaders = varyHeaders;
  this.requestMethod = httpConnection.getRequestMethod();
  this.responseHeaders = RawHeaders.fromMultimap(httpConnection.getHeaderFields(), true);

  SSLSocket sslSocket = getSslSocket(httpConnection);
  if (sslSocket != null) {
    cipherSuite = sslSocket.getSession().getCipherSuite();
    Certificate[] peerCertificatesNonFinal = null;
    try {
      peerCertificatesNonFinal = sslSocket.getSession().getPeerCertificates();
    } catch (SSLPeerUnverifiedException ignored) {
    }
    peerCertificates = peerCertificatesNonFinal;
    localCertificates = sslSocket.getSession().getLocalCertificates();
  } else {
    cipherSuite = null;
    peerCertificates = null;
    localCertificates = null;
  }
}
 
Example #13
Source File: HttpResponseCache.java    From crosswalk-cordova-android with Apache License 2.0 6 votes vote down vote up
public Entry(URI uri, RawHeaders varyHeaders, HttpURLConnection httpConnection)
    throws IOException {
  this.uri = uri.toString();
  this.varyHeaders = varyHeaders;
  this.requestMethod = httpConnection.getRequestMethod();
  this.responseHeaders = RawHeaders.fromMultimap(httpConnection.getHeaderFields(), true);

  SSLSocket sslSocket = getSslSocket(httpConnection);
  if (sslSocket != null) {
    cipherSuite = sslSocket.getSession().getCipherSuite();
    Certificate[] peerCertificatesNonFinal = null;
    try {
      peerCertificatesNonFinal = sslSocket.getSession().getPeerCertificates();
    } catch (SSLPeerUnverifiedException ignored) {
    }
    peerCertificates = peerCertificatesNonFinal;
    localCertificates = sslSocket.getSession().getLocalCertificates();
  } else {
    cipherSuite = null;
    peerCertificates = null;
    localCertificates = null;
  }
}
 
Example #14
Source File: SslRMIServerSocketFactory.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * <p>Creates a server socket that accepts SSL connections
 * configured according to this factory's SSL socket configuration
 * parameters.</p>
 */
public ServerSocket createServerSocket(int port) throws IOException {
    final SSLSocketFactory sslSocketFactory =
            context == null ?
                getDefaultSSLSocketFactory() : context.getSocketFactory();
    return new ServerSocket(port) {
        public Socket accept() throws IOException {
            Socket socket = super.accept();
            SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(
                    socket, socket.getInetAddress().getHostName(),
                    socket.getPort(), true);
            sslSocket.setUseClientMode(false);
            if (enabledCipherSuites != null) {
                sslSocket.setEnabledCipherSuites(enabledCipherSuites);
            }
            if (enabledProtocols != null) {
                sslSocket.setEnabledProtocols(enabledProtocols);
            }
            sslSocket.setNeedClientAuth(needClientAuth);
            return sslSocket;
        }
    };
}
 
Example #15
Source File: RpcSSLSocketFactory.java    From p4ic4idea with Apache License 2.0 6 votes vote down vote up
/**
 * Configure ssl socket.
 * 
 * @param socket
 *            the socket
 * @return the socket
 */
private Socket configureSSLSocket(Socket socket) {
	if (socket != null) {
		if (this.properties == null) {
			this.properties = new Properties();
		}
		boolean setEnabledProtocols = RpcPropertyDefs.getPropertyAsBoolean(properties,
				RpcPropertyDefs.RPC_SECURE_SOCKET_SET_ENABLED_PROTOCOLS_NICK,
				RpcPropertyDefs.RPC_DEFAULT_SECURE_SOCKET_SET_ENABLED_PROTOCOLS);
		if (setEnabledProtocols) {
			String[] enabledProtocols = RpcPropertyDefs.getProperty(properties,
					RpcPropertyDefs.RPC_SECURE_SOCKET_ENABLED_PROTOCOLS_NICK,
					RpcPropertyDefs.RPC_DEFAULT_SECURE_SOCKET_ENABLED_PROTOCOLS).split("\\s*,\\s*");
			((SSLSocket)socket).setEnabledProtocols(enabledProtocols);
		}
	}
	return socket;
}
 
Example #16
Source File: FTPConnection.java    From MinimalFTP with Apache License 2.0 5 votes vote down vote up
public void enableSSL(SSLContext context) throws IOException {
    SSLSocketFactory factory = context.getSocketFactory();
    con = factory.createSocket(con, con.getInetAddress().getHostAddress(), con.getPort(), true);
    ((SSLSocket)con).setUseClientMode(false);

    reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
    writer = new BufferedWriter(new OutputStreamWriter(con.getOutputStream()));
}
 
Example #17
Source File: SslIntegrationTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
private void doConnectionWithAliasTestImpl(String alias, String expectedDN, boolean requestOpenSSL) throws Exception, JMSException, SSLPeerUnverifiedException, IOException {
    TransportOptions sslOptions = new TransportOptions();
    sslOptions.setKeyStoreLocation(BROKER_JKS_KEYSTORE);
    sslOptions.setTrustStoreLocation(BROKER_JKS_TRUSTSTORE);
    sslOptions.setKeyStorePassword(PASSWORD);
    sslOptions.setTrustStorePassword(PASSWORD);
    sslOptions.setVerifyHost(false);

    SSLContext context = TransportSupport.createJdkSslContext(sslOptions);

    try (TestAmqpPeer testPeer = new TestAmqpPeer(context, true);) {
        String connOptions = "?transport.keyStoreLocation=" + CLIENT_MULTI_KEYSTORE + "&" +
                             "transport.keyStorePassword=" + PASSWORD + "&" +
                             "transport.trustStoreLocation=" + CLIENT_JKS_TRUSTSTORE + "&" +
                             "transport.trustStorePassword=" + PASSWORD + "&" +
                             "transport.keyAlias=" + alias + "&" +
                             "transport.useOpenSSL=" + requestOpenSSL;

        Connection connection = testFixture.establishConnecton(testPeer, true, connOptions, null, null, true);

        Socket socket = testPeer.getClientSocket();
        assertTrue(socket instanceof SSLSocket);
        SSLSession session = ((SSLSocket) socket).getSession();

        Certificate[] peerCertificates = session.getPeerCertificates();
        assertNotNull(peerCertificates);

        Certificate cert = peerCertificates[0];
        assertTrue(cert instanceof X509Certificate);
        String dn = ((X509Certificate)cert).getSubjectX500Principal().getName();
        assertEquals("Unexpected certificate DN", expectedDN, dn);

        testPeer.expectClose();
        connection.close();
    }
}
 
Example #18
Source File: AndroidPlatform.java    From AndroidProjects with MIT License 5 votes vote down vote up
@Override public String getSelectedProtocol(SSLSocket socket) {
  if (getAlpnSelectedProtocol == null) return null;
  if (!getAlpnSelectedProtocol.isSupported(socket)) return null;

  byte[] alpnResult = (byte[]) getAlpnSelectedProtocol.invokeWithoutCheckedException(socket);
  return alpnResult != null ? new String(alpnResult, Util.UTF_8) : null;
}
 
Example #19
Source File: TLSProtocolSocketFactory.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Verifies the peer's hostname using the configured {@link HostnameVerifier}.
 * 
 * @param socket the socket connected to the peer whose hostname is to be verified.
 * 
 * @throws SSLException if the hostname does not verify against the peer's certificate, 
 *          or if there is an error in performing the evaluation
 */
protected void verifyHostname(Socket socket) throws SSLException {
    if (hostnameVerifier == null) {
        return;
    }
    
    if (!(socket instanceof SSLSocket)) {
        return;
    }
    
    SSLSocket sslSocket = (SSLSocket) socket;
    
    try {
        SSLSession sslSession = sslSocket.getSession();
        String hostname = sslSession.getPeerHost();
        
        if (!hostnameVerifier.verify(hostname, sslSession)) {
            throw new SSLPeerUnverifiedException("SSL peer failed hostname validation for name: " + hostname);
        }
    } catch (SSLException e) {
        cleanUpFailedSocket(sslSocket);
        throw e;
    } catch (Throwable t) {
        // Make sure we close the socket on any kind of Exception, RuntimeException or Error.
        cleanUpFailedSocket(sslSocket);
        throw new SSLException("Error in hostname verification", t);
    }
}
 
Example #20
Source File: CustomSslSocketFactory.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Socket createSocket(InetAddress paramInetAddress1, int paramInt1, InetAddress paramInetAddress2,
		int paramInt2) throws IOException {

	SSLSocket socket = (SSLSocket) this.sslSocketFactory.createSocket(paramInetAddress1, paramInt1,
			paramInetAddress2, paramInt2);

	if (this.handshakeListener != null) {
		socket.addHandshakeCompletedListener(this.handshakeListener);
	}

	return socket;
}
 
Example #21
Source File: SecureSSLSocketFactory.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
@Override
public Socket createSocket(InetAddress inetAddress, int localPort) throws IOException {
    SSLSocketFactory factory = _sslContext.getSocketFactory();
    Socket socket = factory.createSocket(inetAddress, localPort);
    if (socket instanceof SSLSocket) {
        ((SSLSocket)socket).setEnabledProtocols(SSLUtils.getSupportedProtocols(((SSLSocket)socket).getEnabledProtocols()));
    }
    return socket;
}
 
Example #22
Source File: SslSocketManager.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
static Socket createSocket(final InetSocketAddress socketAddress, final int connectTimeoutMillis,
        final SslConfiguration sslConfiguration, final SocketOptions socketOptions) throws IOException {
    final SSLSocketFactory socketFactory = createSslSocketFactory(sslConfiguration);
    final SSLSocket socket = (SSLSocket) socketFactory.createSocket();
    if (socketOptions != null) {
        // Not sure which options must be applied before or after the connect() call.
        socketOptions.apply(socket);
    }
    socket.connect(socketAddress, connectTimeoutMillis);
    if (socketOptions != null) {
        // Not sure which options must be applied before or after the connect() call.
        socketOptions.apply(socket);
    }
    return socket;
}
 
Example #23
Source File: Jdk9Platform.java    From styT with Apache License 2.0 5 votes vote down vote up
public static Jdk9Platform buildIfSupported() {
  // Find JDK 9 new methods
  try {
    Method setProtocolMethod =
        SSLParameters.class.getMethod("setApplicationProtocols", String[].class);
    Method getProtocolMethod = SSLSocket.class.getMethod("getApplicationProtocol");

    return new Jdk9Platform(setProtocolMethod, getProtocolMethod);
  } catch (NoSuchMethodException ignored) {
    // pre JDK 9
  }

  return null;
}
 
Example #24
Source File: tnvt.java    From tn5250j with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @return true when SSL is used and socket is connected.
 * @see {@link #isConnected()}
 */
public boolean isSslSocket() {
	if (this.connected && this.sock != null && this.sock instanceof SSLSocket) {
		return true;
	} else {
		return false;
	}
}
 
Example #25
Source File: SSLSocketHelper.java    From Pix-Art-Messenger with GNU General Public License v3.0 5 votes vote down vote up
public static void setSecurity(final SSLSocket sslSocket) {
    final String[] supportProtocols;
    final Collection<String> supportedProtocols = new LinkedList<>(
            Arrays.asList(sslSocket.getSupportedProtocols()));
    supportedProtocols.remove("SSLv3");
    supportProtocols = supportedProtocols.toArray(new String[supportedProtocols.size()]);

    sslSocket.setEnabledProtocols(supportProtocols);

    final String[] cipherSuites = CryptoHelper.getOrderedCipherSuites(
            sslSocket.getSupportedCipherSuites());
    if (cipherSuites.length > 0) {
        sslSocket.setEnabledCipherSuites(cipherSuites);
    }
}
 
Example #26
Source File: HttpsURLConnectionImpl.java    From reader with MIT License 5 votes vote down vote up
private SSLSocket getSslSocket() {
  if (delegate.httpEngine == null || !delegate.httpEngine.connected) {
    throw new IllegalStateException("Connection has not yet been established");
  }
  return delegate.httpEngine instanceof HttpsEngine
      ? ((HttpsEngine) delegate.httpEngine).getSslSocket()
      : null; // Not HTTPS! Probably an https:// to http:// redirect.
}
 
Example #27
Source File: BinarySecureClientPoolFactory.java    From product-microgateway with Apache License 2.0 5 votes vote down vote up
@Override
public Object createClient(String protocol, String hostName, int port) throws DataEndpointException {
    if (protocol.equalsIgnoreCase(DataEndpointConfiguration.Protocol.SSL.toString())) {
        int timeout = AgentHolder.getInstance().getDataEndpointAgent().getAgentConfiguration()
                .getSocketTimeoutMS();
        String sslProtocols = AgentHolder.getInstance().getDataEndpointAgent().getAgentConfiguration()
                .getSslEnabledProtocols();
        String ciphers = AgentHolder.getInstance().getDataEndpointAgent().getAgentConfiguration().getCiphers();

        try {
            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.replaceAll(" ", "").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.");
    }
}
 
Example #28
Source File: SSLSocketCompatFactory.java    From Yuan-WanAndroid with Apache License 2.0 5 votes vote down vote up
private void upgradeTLS(SSLSocket ssl) {
    // Android 5.0+ (API level21) provides reasonable default settings
    // but it still allows SSLv3
    // https://developer.android.com/about/versions/android-5.0-changes.html#ssl
    if (protocols != null) {
        ssl.setEnabledProtocols(protocols);
    }
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP && cipherSuites != null) {
        ssl.setEnabledCipherSuites(cipherSuites);
    }
}
 
Example #29
Source File: URLConnectionTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@Override
public SSLSocket createSocket(String host, int port)
        throws IOException, UnknownHostException {
    SSLSocket socket = (SSLSocket) delegate.createSocket(host, port);
    socket.setEnabledProtocols(protocols);
    return socket;
}
 
Example #30
Source File: SMTPServer.java    From subethasmtp with Apache License 2.0 5 votes vote down vote up
/**
 * Create a SSL socket that wraps the existing socket. This method
 * is called after the client issued the STARTTLS command.
 * <p>
 * Subclasses may override this method to configure the key stores, enabled protocols/
 * cipher suites, enforce client authentication, etc.
 *
 * @param socket the existing socket as created by {@link #createServerSocket()} (not null)
 * @return a SSLSocket
 * @throws IOException when creating the socket failed
 */
public SSLSocket createSSLSocket(Socket socket) throws IOException
{
	SSLSocketFactory sf = ((SSLSocketFactory) SSLSocketFactory.getDefault());
	InetSocketAddress remoteAddress = (InetSocketAddress) socket.getRemoteSocketAddress();
	SSLSocket s = (SSLSocket) (sf.createSocket(socket, remoteAddress.getHostName(), socket.getPort(), true));

	// we are a server
	s.setUseClientMode(false);

	// allow all supported cipher suites
	s.setEnabledCipherSuites(s.getSupportedCipherSuites());

	return s;
}