Java Code Examples for javax.net.ssl.SSLSocketFactory#getDefault()

The following examples show how to use javax.net.ssl.SSLSocketFactory#getDefault() . 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: GfxdTSSLSocketFactory.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Get a configured SSL socket connected to the specified host and port.
 * <p>
 * If SSLSocketParameters are not null, then they are used to set the values
 * for the algorithms, keystore, truststore and other settings.
 * <p>
 * Else if SSLSocketParameters are null then the default settings are used.
 * Default settings are retrieved from System properties that are set.
 * 
 * Example system properties: -Djavax.net.ssl.trustStore=<truststore location>
 * -Djavax.net.ssl.trustStorePassword=password
 * -Djavax.net.ssl.keyStore=<keystore location>
 * -Djavax.net.ssl.keyStorePassword=password
 * <p>
 * All the client methods return a bound connection, so there is no need to
 * call open() on the TTransport.
 */
public static SSLSocket getClientSocket(InetAddress hostAddress, int port,
    int timeout, SocketParameters params) throws TTransportException {
  if (params == null) {
    SSLSocketFactory factory = (SSLSocketFactory)SSLSocketFactory
        .getDefault();
    return createClient(factory, hostAddress, port, timeout, null);
  }
  else {
    if (!(params.isSSLKeyStoreSet() || params.isSSLTrustStoreSet())) {
      throw new TTransportException(
          "Either one of the KeyStore or TrustStore must be set "
              + "for SSLSocketParameters");
    }

    SSLContext ctx = createSSLContext(params);
    return createClient(ctx.getSocketFactory(), hostAddress, port, timeout,
        params);
  }
}
 
Example 2
Source File: CloseSocket.java    From openjdk-jdk9 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 3
Source File: Fix5070632.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // reserve the security properties
    String reservedSFacProvider =
        Security.getProperty("ssl.SocketFactory.provider");

    // use a non-existing provider so that the DefaultSSLSocketFactory
    // will be used, and then test against it.

    Security.setProperty("ssl.SocketFactory.provider", "foo.NonExistant");
    SSLSocketFactory fac = (SSLSocketFactory)SSLSocketFactory.getDefault();
    try {
        fac.createSocket();
    } catch(SocketException se) {
        // if exception caught, then it's ok
        System.out.println("Throw SocketException");
        se.printStackTrace();
        return;
    } finally {
        // restore the security properties
        if (reservedSFacProvider == null) {
            reservedSFacProvider = "";
        }
        Security.setProperty("ssl.SocketFactory.provider",
                                            reservedSFacProvider);
    }

    // if not caught, or other exception caught, then it's error
    throw new Exception("should throw SocketException");
}
 
Example 4
Source File: SSLChannel.java    From yajsync with GNU General Public License v3.0 5 votes vote down vote up
public static SSLChannel open(String address, int port, int contimeout,
                              int timeout)
        throws IOException
{
    SocketFactory factory = SSLSocketFactory.getDefault();
    InetSocketAddress socketAddress = new InetSocketAddress(address, port);
    Socket sock = factory.createSocket();
    sock.connect(socketAddress, contimeout);
    return new SSLChannel((SSLSocket) sock, timeout);
}
 
Example 5
Source File: CipherTestUtils.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private CipherTestUtils()
        throws IOException, FileNotFoundException, KeyStoreException,
        NoSuchAlgorithmException, CertificateException,
        UnrecoverableKeyException, InvalidKeySpecException {
    factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
    KeyStore serverKeyStore = createServerKeyStore(SERVER_PUBLIC_KEY,
            SERVER_PRIVATE_KEY);
    KeyStore serverTrustStore = createServerKeyStore(CA_PUBLIC_KEY,
            CA_PRIVATE_KEY);

    if (serverKeyStore != null) {
        KeyManagerFactory keyFactory1
                = KeyManagerFactory.getInstance(
                        KeyManagerFactory.getDefaultAlgorithm());
        keyFactory1.init(serverKeyStore, PASSWORD);
        serverKeyManager = (X509ExtendedKeyManager) keyFactory1.
                getKeyManagers()[0];
    } else {
        serverKeyManager = null;
    }
    serverTrustManager = serverTrustStore != null
            ? new AlwaysTrustManager(serverTrustStore) : null;

    KeyStore clientKeyStore, clientTrustStore;
    clientTrustStore = serverTrustStore;
    clientKeyStore =
            createServerKeyStore(CLIENT_PUBLIC_KEY,CLIENT_PRIVATE_KEY);
    if (clientKeyStore != null) {
        KeyManagerFactory keyFactory
                = KeyManagerFactory.getInstance(
                        KeyManagerFactory.getDefaultAlgorithm());
        keyFactory.init(clientKeyStore, PASSWORD);
        clientKeyManager = (X509ExtendedKeyManager) keyFactory.
                getKeyManagers()[0];
    } else {
        clientKeyManager = null;
    }
    clientTrustManager = (clientTrustStore != null)
            ? new AlwaysTrustManager(clientTrustStore) : null;
}
 
Example 6
Source File: ValuesCustomizer.java    From visualvm with GNU General Public License v2.0 5 votes vote down vote up
synchronized String[] allValues() {
    if (allValues == null) {
    SocketFactory f = SSLSocketFactory.getDefault();
        if (!(f instanceof SSLSocketFactory)) allValues = new String[0];
        allValues = ((SSLSocketFactory)f).getSupportedCipherSuites();
    }
    return allValues;
}
 
Example 7
Source File: GenericStreamCipher.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
void doClientSide() throws Exception {

        /*
         * Wait for server to get started.
         */
        while (!serverReady) {
            Thread.sleep(50);
        }

        SSLSocketFactory sslsf =
            (SSLSocketFactory) SSLSocketFactory.getDefault();
        SSLSocket sslSocket = (SSLSocket)
            sslsf.createSocket("localhost", serverPort);

        // enable TLSv1.1 only
        sslSocket.setEnabledProtocols(new String[] {"TLSv1.1"});

        // enable a stream cipher
        sslSocket.setEnabledCipherSuites(
            new String[] {"SSL_RSA_WITH_RC4_128_MD5"});

        InputStream sslIS = sslSocket.getInputStream();
        OutputStream sslOS = sslSocket.getOutputStream();

        sslOS.write('B');
        sslOS.flush();
        sslIS.read();

        sslSocket.close();
    }
 
Example 8
Source File: ApplicationSSLSocketFactory.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * ApplicationSSLSocketFactory constructor.  
 * SSLContext initialization will be performed using {@link SSLContextInitializer}.
 */
public ApplicationSSLSocketFactory() {
	SSLSocketFactory factory = null;
	try {
		if (SSLContextInitializer.initialize()) {
			factory = SSLContext.getDefault().getSocketFactory();
		}
	}
	catch (NoSuchAlgorithmException e) {
		Msg.error(this, "Failed to employ default SSLContext: " + e.toString(), e);
	}
	this.socketFactory =
		factory != null ? factory : (SSLSocketFactory) SSLSocketFactory.getDefault();
}
 
Example 9
Source File: GenericBlockCipher.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
void doClientSide() throws Exception {

        /*
         * Wait for server to get started.
         */
        while (!serverReady) {
            Thread.sleep(50);
        }

        SSLSocketFactory sslsf =
            (SSLSocketFactory) SSLSocketFactory.getDefault();
        SSLSocket sslSocket = (SSLSocket)
            sslsf.createSocket("localhost", serverPort);

        // enable TLSv1.1 only
        sslSocket.setEnabledProtocols(new String[] {"TLSv1.1"});

        // enable a block cipher
        sslSocket.setEnabledCipherSuites(
            new String[] {"TLS_RSA_WITH_AES_128_CBC_SHA"});

        InputStream sslIS = sslSocket.getInputStream();
        OutputStream sslOS = sslSocket.getOutputStream();

        sslOS.write('B');
        sslOS.flush();
        sslIS.read();

        sslSocket.close();
    }
 
Example 10
Source File: Fix5070632.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // reserve the security properties
    String reservedSFacProvider =
        Security.getProperty("ssl.SocketFactory.provider");

    // use a non-existing provider so that the DefaultSSLSocketFactory
    // will be used, and then test against it.

    Security.setProperty("ssl.SocketFactory.provider", "foo.NonExistant");
    SSLSocketFactory fac = (SSLSocketFactory)SSLSocketFactory.getDefault();
    try {
        fac.createSocket();
    } catch(SocketException se) {
        // if exception caught, then it's ok
        System.out.println("Throw SocketException");
        se.printStackTrace();
        return;
    } finally {
        // restore the security properties
        if (reservedSFacProvider == null) {
            reservedSFacProvider = "";
        }
        Security.setProperty("ssl.SocketFactory.provider",
                                            reservedSFacProvider);
    }

    // if not caught, or other exception caught, then it's error
    throw new Exception("should throw SocketException");
}
 
Example 11
Source File: Fix5070632.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // reserve the security properties
    String reservedSFacProvider =
        Security.getProperty("ssl.SocketFactory.provider");

    // use a non-existing provider so that the DefaultSSLSocketFactory
    // will be used, and then test against it.

    Security.setProperty("ssl.SocketFactory.provider", "foo.NonExistant");
    SSLSocketFactory fac = (SSLSocketFactory)SSLSocketFactory.getDefault();
    try {
        fac.createSocket();
    } catch(SocketException se) {
        // if exception caught, then it's ok
        System.out.println("Throw SocketException");
        se.printStackTrace();
        return;
    } finally {
        // restore the security properties
        if (reservedSFacProvider == null) {
            reservedSFacProvider = "";
        }
        Security.setProperty("ssl.SocketFactory.provider",
                                            reservedSFacProvider);
    }

    // if not caught, or other exception caught, then it's error
    throw new Exception("should throw SocketException");
}
 
Example 12
Source File: CipherTestUtils.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
private CipherTestUtils()
        throws IOException, FileNotFoundException, KeyStoreException,
        NoSuchAlgorithmException, CertificateException,
        UnrecoverableKeyException, InvalidKeySpecException {
    factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
    KeyStore serverKeyStore = createServerKeyStore(SERVER_PUBLIC_KEY,
            SERVER_PRIVATE_KEY);
    KeyStore serverTrustStore = createServerKeyStore(CA_PUBLIC_KEY,
            CA_PRIVATE_KEY);

    if (serverKeyStore != null) {
        KeyManagerFactory keyFactory1
                = KeyManagerFactory.getInstance(
                        KeyManagerFactory.getDefaultAlgorithm());
        keyFactory1.init(serverKeyStore, PASSWORD);
        serverKeyManager = (X509ExtendedKeyManager) keyFactory1.
                getKeyManagers()[0];
    } else {
        serverKeyManager = null;
    }
    serverTrustManager = serverTrustStore != null
            ? new AlwaysTrustManager(serverTrustStore) : null;

    KeyStore clientKeyStore, clientTrustStore;
    clientTrustStore = serverTrustStore;
    clientKeyStore =
            createServerKeyStore(CLIENT_PUBLIC_KEY,CLIENT_PRIVATE_KEY);
    if (clientKeyStore != null) {
        KeyManagerFactory keyFactory
                = KeyManagerFactory.getInstance(
                        KeyManagerFactory.getDefaultAlgorithm());
        keyFactory.init(clientKeyStore, PASSWORD);
        clientKeyManager = (X509ExtendedKeyManager) keyFactory.
                getKeyManagers()[0];
    } else {
        clientKeyManager = null;
    }
    clientTrustManager = (clientTrustStore != null)
            ? new AlwaysTrustManager(clientTrustStore) : null;
}
 
Example 13
Source File: Fix5070632.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // reserve the security properties
    String reservedSFacProvider =
        Security.getProperty("ssl.SocketFactory.provider");

    // use a non-existing provider so that the DefaultSSLSocketFactory
    // will be used, and then test against it.

    Security.setProperty("ssl.SocketFactory.provider", "foo.NonExistant");
    SSLSocketFactory fac = (SSLSocketFactory)SSLSocketFactory.getDefault();
    try {
        fac.createSocket();
    } catch(SocketException se) {
        // if exception caught, then it's ok
        System.out.println("Throw SocketException");
        se.printStackTrace();
        return;
    } finally {
        // restore the security properties
        if (reservedSFacProvider == null) {
            reservedSFacProvider = "";
        }
        Security.setProperty("ssl.SocketFactory.provider",
                                            reservedSFacProvider);
    }

    // if not caught, or other exception caught, then it's error
    throw new Exception("should throw SocketException");
}
 
Example 14
Source File: SslRMIClientSocketFactory.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
private static synchronized SocketFactory getDefaultClientSocketFactory() {
    if (defaultSocketFactory == null)
        defaultSocketFactory = SSLSocketFactory.getDefault();
    return defaultSocketFactory;
}
 
Example 15
Source File: SparkplugExample.java    From Sparkplug with Eclipse Public License 1.0 4 votes vote down vote up
public void run() {
	try {
		// Random generator and thread pool for outgoing published messages
		executor = Executors.newFixedThreadPool(1);
		
		// Build up DEATH payload - note DEATH payloads don't have a regular sequence number
		SparkplugBPayloadBuilder deathPayload = new SparkplugBPayloadBuilder().setTimestamp(new Date());
		deathPayload = addBdSeqNum(deathPayload);
		byte [] deathBytes = new SparkplugBPayloadEncoder().getBytes(deathPayload.createPayload());
		
		MqttConnectOptions options = new MqttConnectOptions();
		
		if (USING_REAL_TLS) {
			SocketFactory sf = SSLSocketFactory.getDefault();
			options.setSocketFactory(sf);
		}
		
		// Connect to the MQTT Server
		options.setAutomaticReconnect(true);
		options.setCleanSession(true);
		options.setConnectionTimeout(30);
		options.setKeepAliveInterval(30);
		options.setUserName(username);
		options.setPassword(password.toCharArray());
		options.setWill(NAMESPACE + "/" + groupId + "/NDEATH/" + edgeNode, deathBytes, 0, false);
		client = new MqttClient(serverUrl, clientId);
		client.setTimeToWait(30000);	
		client.setCallback(this);					// short timeout on failure to connect
		client.connect(options);
		
		// Subscribe to control/command messages for both the edge of network node and the attached devices
		client.subscribe(NAMESPACE + "/" + groupId + "/NCMD/" + edgeNode + "/#", 0);
		client.subscribe(NAMESPACE + "/" + groupId + "/DCMD/" + edgeNode + "/#", 0);
		

		List<Metric> nodeMetrics = new ArrayList<Metric>();
		List<Metric> deviceMetrics = new ArrayList<Metric>();
		
		// Loop forever publishing data every PUBLISH_PERIOD
		while (true) {
			Thread.sleep(PUBLISH_PERIOD);
			
			synchronized(seqLock) {
				if (client.isConnected()) {

					System.out.println("Time: " + calendar.getTimeInMillis() + "  Index: " + index);
					
					// Add a 'real time' metric
					nodeMetrics.add(new MetricBuilder("MyNodeMetric", Int32, index)
							.timestamp(calendar.getTime())
							.createMetric());

					// Add a 'real time' metric
					deviceMetrics.add(new MetricBuilder("MyDeviceMetric", Int32, index+50)
							.timestamp(calendar.getTime())
							.createMetric());

					// Publish, increment the calendar and index and reset
					calendar.add(Calendar.MILLISECOND, 1);
					if (index == 50) {
						index = 0;
						
						System.out.println("nodeMetrics: " + nodeMetrics.size());
						System.out.println("deviceMetrics: " + deviceMetrics.size());

						SparkplugBPayload nodePayload = new SparkplugBPayload(
								new Date(), 
								nodeMetrics, 
								getSeqNum(),
								null, 
								null);
						
						client.publish(NAMESPACE + "/" + groupId + "/NDATA/" + edgeNode, 
								new SparkplugBPayloadEncoder().getBytes(nodePayload), 0, false);
						
						SparkplugBPayload devicePayload = new SparkplugBPayload(
								new Date(),
								deviceMetrics,
								getSeqNum(),
								null, 
								null);

						client.publish(NAMESPACE + "/" + groupId + "/DDATA/" + edgeNode + "/" + deviceId, 
								new SparkplugBPayloadEncoder().getBytes(devicePayload), 0, false);
						
						nodeMetrics = new ArrayList<Metric>();
						deviceMetrics = new ArrayList<Metric>();
					} else {
						index++;
					}
				} else {
					System.out.println("Not connected - not publishing data");
				}
			}
		}
	} catch(Exception e) {
		e.printStackTrace();
	}
}
 
Example 16
Source File: SslRMIClientSocketFactory.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
private static synchronized SocketFactory getDefaultClientSocketFactory() {
    if (defaultSocketFactory == null)
        defaultSocketFactory = SSLSocketFactory.getDefault();
    return defaultSocketFactory;
}
 
Example 17
Source File: SSLTCPNetSyslogWriter.java    From syslog4j-graylog2 with GNU Lesser General Public License v2.1 4 votes vote down vote up
protected SocketFactory obtainSocketFactory() {
    return SSLSocketFactory.getDefault();
}
 
Example 18
Source File: SSLSocketTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
public void test_SSLSocket_getEnabledCipherSuites_returnsCopies() throws Exception {
    SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
    SSLSocket ssl = (SSLSocket) sf.createSocket();
    assertNotSame(ssl.getEnabledCipherSuites(), ssl.getEnabledCipherSuites());
}
 
Example 19
Source File: SparkplugExample.java    From Sparkplug with Eclipse Public License 1.0 4 votes vote down vote up
public void run() {
	try {
		// Random generator and thread pool for outgoing published messages
		executor = Executors.newFixedThreadPool(1);

		// Build up DEATH payload - note DEATH payloads don't have a regular sequence number
		SparkplugBPayloadBuilder deathPayload = new SparkplugBPayloadBuilder().setTimestamp(new Date());
		deathPayload = addBdSeqNum(deathPayload);
		byte[] deathBytes = new SparkplugBPayloadEncoder().getBytes(deathPayload.createPayload());

		MqttConnectOptions options = new MqttConnectOptions();

		if (USING_REAL_TLS) {
			SocketFactory sf = SSLSocketFactory.getDefault();
			options.setSocketFactory(sf);
		}

		// Connect to the MQTT Server
		options.setAutomaticReconnect(true);
		options.setCleanSession(true);
		options.setConnectionTimeout(30);
		options.setKeepAliveInterval(30);
		options.setUserName(username);
		options.setPassword(password.toCharArray());
		options.setWill(NAMESPACE + "/" + groupId + "/NDEATH/" + edgeNode, deathBytes, 0, false);
		client = new MqttClient(serverUrl, clientId);
		client.setTimeToWait(2000);
		client.setCallback(this); // short timeout on failure to connect
		client.connect(options);

		// Subscribe to control/command messages for both the edge of network node and the attached devices
		client.subscribe(NAMESPACE + "/" + groupId + "/NCMD/" + edgeNode + "/#", 0);
		client.subscribe(NAMESPACE + "/" + groupId + "/DCMD/" + edgeNode + "/#", 0);

		// Loop forever publishing data every PUBLISH_PERIOD
		while (true) {
			Thread.sleep(PUBLISH_PERIOD);

			if (client.isConnected()) {
				synchronized (seqLock) {
					System.out.println("Connected - publishing new data");
					// Create the payload and add some metrics
					SparkplugBPayload payload = new SparkplugBPayload(new Date(), newComplexTemplateInstance(),
							getSeqNum(), newUUID(), null);

					client.publish(NAMESPACE + "/" + groupId + "/DDATA/" + edgeNode + "/" + deviceId,
							new SparkplugBPayloadEncoder().getBytes(payload), 0, false);
				}
			} else {
				System.out.println("Not connected - not publishing data");
			}
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 20
Source File: SslRMIClientSocketFactory.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
private static synchronized SocketFactory getDefaultClientSocketFactory() {
    if (defaultSocketFactory == null)
        defaultSocketFactory = SSLSocketFactory.getDefault();
    return defaultSocketFactory;
}