Java Code Examples for javax.net.ssl.SSLSocketFactory

The following examples show how to use javax.net.ssl.SSLSocketFactory. These examples are extracted from open source projects. 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 Project: jdk9-jigsaw   Source File: Client.java    License: Creative Commons Zero v1.0 Universal 7 votes vote down vote up
public static void main(String[] args) throws InterruptedException {
	
	try {
		System.setProperty("javax.net.ssl.trustStore", "C:/Users/Martin/sample.pfx");
		System.setProperty("javax.net.ssl.trustStorePassword", "sample");

		SSLSocketFactory ssf = (SSLSocketFactory) SSLSocketFactory.getDefault();
		SSLSocket s = (SSLSocket) ssf.createSocket("127.0.0.1", 4444);
		SSLParameters params = s.getSSLParameters();
		s.setSSLParameters(params);
		
		PrintWriter out = new PrintWriter(s.getOutputStream(), true);
		out.println("Hi, server.");
		BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
		String x = in.readLine();
		System.out.println(x);
		System.out.println("Used protocol: " + s.getApplicationProtocol());
		
		out.close();
		in.close();
		s.close();
	} catch (Exception ex) {
		ex.printStackTrace();
	}
	
}
 
Example 2
/**
 * <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 3
Source Project: developerWorks   Source File: MainActivity.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns the SSLSocketFactory to use to connect to the MQTT server over ssl://
 * @param context The ApplicationContext to use
 * @return SSLSocketFactory
 */
private SSLSocketFactory getSSLSocketFactory(Context context) {
    SSLSocketFactory factory = null;
    try {
        ProviderInstaller.installIfNeeded(context);

        SSLContext sslContext;
        KeyStore ks = KeyStore.getInstance("bks");
        ks.load(context.getResources().openRawResource(R.raw.iot), "password".toCharArray());
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
        tmf.init(ks);
        TrustManager[] tm = tmf.getTrustManagers();
        sslContext = SSLContext.getInstance("TLSv1.2");
        sslContext.init(null, tm, null);
        factory = sslContext.getSocketFactory();
    } catch (Exception e) {
        String notificationMessage = "Exception thrown trying to get SSLSocketFactory: ";
        Log.e(TAG, notificationMessage, e);
        // Store this in the Notification deque
        pushNotification(notificationMessage);
    }
    return factory;
}
 
Example 4
Source Project: jgroups-kubernetes   Source File: TokenStreamProvider.java    License: Apache License 2.0 6 votes vote down vote up
private SSLSocketFactory getSSLSocketFactory() throws IOException {
    if(this.factory == null) {
        synchronized(this) {
            if(this.factory == null) {
                try {
                    TrustManager[] trustManagers = configureCaCert(this.caCertFile);
                    SSLContext context = SSLContext.getInstance("TLS");
                    context.init(null, trustManagers, null);
                    this.factory = context.getSocketFactory();
                } catch(Exception e) {
                    throw new IOException(e);
                }
            }
        }
    }
    return this.factory;
}
 
Example 5
Source Project: carbon-device-mgt   Source File: Utils.java    License: Apache License 2.0 6 votes vote down vote up
private static SSLSocketFactory getTrustedSSLSocketFactory() {
    try {
        String keyStorePassword = ServerConfiguration.getInstance().getFirstProperty("Security.KeyStore.Password");
        String keyStoreLocation = ServerConfiguration.getInstance().getFirstProperty("Security.KeyStore.Location");
        String trustStorePassword = ServerConfiguration.getInstance().getFirstProperty(
                "Security.TrustStore.Password");
        String trustStoreLocation = ServerConfiguration.getInstance().getFirstProperty(
                "Security.TrustStore.Location");
        KeyStore keyStore = loadKeyStore(keyStoreLocation,keyStorePassword,KEY_STORE_TYPE);
        KeyStore trustStore = loadTrustStore(trustStoreLocation,trustStorePassword);

        return initSSLConnection(keyStore,keyStorePassword,trustStore);
    } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException
            |CertificateException | IOException | UnrecoverableKeyException e) {
        log.error("Error while creating the SSL socket factory due to "+e.getMessage(),e);
        return null;
    }

}
 
Example 6
Source Project: grpc-nebula-java   Source File: OkHttpClientTransport.java    License: Apache License 2.0 6 votes vote down vote up
OkHttpClientTransport(InetSocketAddress address, String authority, @Nullable String userAgent,
    Executor executor, @Nullable SSLSocketFactory sslSocketFactory,
    @Nullable HostnameVerifier hostnameVerifier, ConnectionSpec connectionSpec,
    int maxMessageSize, int initialWindowSize, @Nullable ProxyParameters proxy,
    Runnable tooManyPingsRunnable, int maxInboundMetadataSize, TransportTracer transportTracer) {
  this.address = Preconditions.checkNotNull(address, "address");
  this.defaultAuthority = authority;
  this.maxMessageSize = maxMessageSize;
  this.initialWindowSize = initialWindowSize;
  this.executor = Preconditions.checkNotNull(executor, "executor");
  serializingExecutor = new SerializingExecutor(executor);
  // Client initiated streams are odd, server initiated ones are even. Server should not need to
  // use it. We start clients at 3 to avoid conflicting with HTTP negotiation.
  nextStreamId = 3;
  this.sslSocketFactory = sslSocketFactory;
  this.hostnameVerifier = hostnameVerifier;
  this.connectionSpec = Preconditions.checkNotNull(connectionSpec, "connectionSpec");
  this.stopwatchFactory = GrpcUtil.STOPWATCH_SUPPLIER;
  this.userAgent = GrpcUtil.getGrpcUserAgent("okhttp", userAgent);
  this.proxy = proxy;
  this.tooManyPingsRunnable =
      Preconditions.checkNotNull(tooManyPingsRunnable, "tooManyPingsRunnable");
  this.maxInboundMetadataSize = maxInboundMetadataSize;
  this.transportTracer = Preconditions.checkNotNull(transportTracer);
  initTransportTracer();
}
 
Example 7
Source Project: grpc-nebula-java   Source File: OkHttpTlsUpgrader.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Upgrades given Socket to be a SSLSocket.
 *
 * @throws IOException if an IO error was encountered during the upgrade handshake.
 * @throws RuntimeException if the upgrade negotiation failed.
 */
public static SSLSocket upgrade(SSLSocketFactory sslSocketFactory,
    HostnameVerifier hostnameVerifier, Socket socket, String host, int port,
    ConnectionSpec spec) throws IOException {
  Preconditions.checkNotNull(sslSocketFactory, "sslSocketFactory");
  Preconditions.checkNotNull(socket, "socket");
  Preconditions.checkNotNull(spec, "spec");
  SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(
      socket, host, port, true /* auto close */);
  spec.apply(sslSocket, false);
  String negotiatedProtocol = OkHttpProtocolNegotiator.get().negotiate(
      sslSocket, host, spec.supportsTlsExtensions() ? TLS_PROTOCOLS : null);
  Preconditions.checkState(
      TLS_PROTOCOLS.contains(Protocol.get(negotiatedProtocol)),
      "Only " + TLS_PROTOCOLS + " are supported, but negotiated protocol is %s",
      negotiatedProtocol);

  if (hostnameVerifier == null) {
    hostnameVerifier = OkHostnameVerifier.INSTANCE;
  }
  if (!hostnameVerifier.verify(canonicalizeHost(host), sslSocket.getSession())) {
    throw new SSLPeerUnverifiedException("Cannot verify hostname: " + host);
  }
  return sslSocket;
}
 
Example 8
Source Project: http2-examples   Source File: OkHttpClientExample.java    License: Apache License 2.0 6 votes vote down vote up
private static OkHttpClient getUnsafeOkHttpClient() {
    try {
        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, TRUST_ALL_CERTS, new java.security.SecureRandom());
        // Create an ssl socket factory with our all-trusting manager
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.setSslSocketFactory(sslSocketFactory);
        okHttpClient.setHostnameVerifier((hostname, session) -> true);

        return okHttpClient;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 9
Source Project: openjdk-jdk8u   Source File: CloseSocket.java    License: 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 10
Source Project: ssltest   Source File: SSLTest.java    License: Apache License 2.0 6 votes vote down vote up
private static SSLSocket createSSLSocket(InetSocketAddress address,
                                         String host,
                                         int port,
                                         int readTimeout,
                                         int connectTimeout,
                                         SSLSocketFactory sf)
    throws IOException
{
    //
    // Note: SSLSocketFactory has several create() methods.
    // Those that take arguments all connect immediately
    // and have no options for specifying a connection timeout.
    //
    // So, we have to create a socket and connect it (with a
    // connection timeout), then have the SSLSocketFactory wrap
    // the already-connected socket.
    //
    Socket sock = new Socket();
    sock.setSoTimeout(readTimeout);
    sock.connect(address, connectTimeout);

    // Wrap plain socket in an SSL socket
    return (SSLSocket)sf.createSocket(sock, host, port, true);
}
 
Example 11
Source Project: ghidra   Source File: RemoteBlockStreamHandle.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Invoked by client during the openBlockStream operation and completes the
 * connection into the server.
 * @return connected socket
 * @throws IOException
 */
protected Socket connect() throws IOException {

	synchronized (this) {
		if (!connectionPending) {
			throw new IOException("already connected");
		}
		connectionPending = false;
	}

	SocketFactory socketFactory = SSLSocketFactory.getDefault();
	Socket socket = socketFactory.createSocket(streamServerIPAddress, streamServerPort);

	// TODO: set socket options ?

	// write stream connection request info
	OutputStream out = socket.getOutputStream();
	out.write(getStreamRequestHeader().getBytes());
	out.flush();

	return socket;
}
 
Example 12
Source Project: TrustKit-Android   Source File: SSLSocketFactoryTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testPinnedDomainSuccessAnchor() throws IOException {
    String serverHostname = "www.datatheorem.com";
    TestableTrustKit.initializeWithNetworkSecurityConfiguration(
            InstrumentationRegistry.getInstrumentation().getContext(), mockReporter);

    // Create a TrustKit SocketFactory and ensure the connection succeeds
    SSLSocketFactory test = TestableTrustKit.getInstance().getSSLSocketFactory(serverHostname);
    Socket socket = test.createSocket(serverHostname, 443);
    socket.getInputStream();

    assertTrue(socket.isConnected());
    socket.close();

    // Ensure the background reporter was NOT called
    verify(mockReporter, never()).pinValidationFailed(
            eq(serverHostname),
            eq(0),
            (List<X509Certificate>) org.mockito.Matchers.isNotNull(),
            (List<X509Certificate>) org.mockito.Matchers.isNotNull(),
            eq(TestableTrustKit.getInstance().getConfiguration().getPolicyForHostname(serverHostname)),
            eq(PinningValidationResult.FAILED)
    );
}
 
Example 13
Source Project: openjdk-jdk9   Source File: CloseSocket.java    License: 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 14
private synchronized SSLSocketFactory getDelegate() {
    // Relax the SSL check if instructed (for this factory, or systemwide)
    if (!mSecure || isSslCheckRelaxed()) {
        if (mInsecureFactory == null) {
            if (mSecure) {
                Log.w(TAG, "*** BYPASSING SSL SECURITY CHECKS (socket.relaxsslcheck=yes) ***");
            } else {
                Log.w(TAG, "Bypassing SSL security checks at caller's request");
            }
            mInsecureFactory = makeSocketFactory(mKeyManagers, INSECURE_TRUST_MANAGER);
        }
        return mInsecureFactory;
    } else {
        if (mSecureFactory == null) {
            mSecureFactory = makeSocketFactory(mKeyManagers, mTrustManagers);
        }
        return mSecureFactory;
    }
}
 
Example 15
Source Project: nv-websocket-client   Source File: SocketFactorySettings.java    License: Apache License 2.0 6 votes vote down vote up
public SocketFactory selectSocketFactory(boolean secure)
{
    if (secure)
    {
        if (mSSLContext != null)
        {
            return mSSLContext.getSocketFactory();
        }

        if (mSSLSocketFactory != null)
        {
            return mSSLSocketFactory;
        }

        return SSLSocketFactory.getDefault();
    }

    if (mSocketFactory != null)
    {
        return mSocketFactory;
    }

    return SocketFactory.getDefault();
}
 
Example 16
Source Project: JDKSourceCode1.8   Source File: SslRMIServerSocketFactory.java    License: MIT License 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 17
@Override
public Socket accept() throws IOException {
    final SSLSocketFactory sslSocketFactory =
            context == null ?
                getDefaultSSLSocketFactory() : context.getSocketFactory();
    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 18
Source Project: j2objc   Source File: SSLSocketTest.java    License: Apache License 2.0 5 votes vote down vote up
public void test_SSLSocket_getSession() throws Exception {
    SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
    SSLSocket ssl = (SSLSocket) sf.createSocket();
    SSLSession session = ssl.getSession();
    assertNotNull(session);
    assertFalse(session.isValid());
}
 
Example 19
Source Project: TrustKit-Android   Source File: OkHttp2Helper.java    License: MIT License 5 votes vote down vote up
/**
 * Retrieve an {@code SSLSSocketFactory} that implements SSL pinning validation based on the
 * current TrustKit configuration. It can be used with an OkHttpClient to add SSL
 * pinning validation to the connections.
 *
 * <p>
 * The {@code SSLSocketFactory} is configured for the current TrustKit configuration and
 * will enforce the configuration's pinning policy.
 * </p>
 */
@NonNull
public static SSLSocketFactory getSSLSocketFactory() {
    try {
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, new X509TrustManager[]{trustManager}, null);

        return sslContext.getSocketFactory();
    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        e.printStackTrace();
        throw new IllegalStateException("SSLSocketFactory creation failed");
    }
}
 
Example 20
Source Project: openjdk-jdk9   Source File: JSSEClient.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    System.out.println("Client: arguments=" + String.join("; ", args));

    int port = Integer.valueOf(args[0]);
    String[] trustNames = args[1].split(TLSRestrictions.DELIMITER);
    String[] certNames = args[2].split(TLSRestrictions.DELIMITER);
    String constraint = args[3];

    TLSRestrictions.setConstraint("Client", constraint);

    SSLContext context = TLSRestrictions.createSSLContext(
            trustNames, certNames);
    SSLSocketFactory socketFactory = context.getSocketFactory();
    try (SSLSocket socket = (SSLSocket) socketFactory.createSocket()) {
        socket.connect(new InetSocketAddress("localhost", port),
                TLSRestrictions.TIMEOUT);
        socket.setSoTimeout(TLSRestrictions.TIMEOUT);
        System.out.println("Client: connected");

        InputStream sslIS = socket.getInputStream();
        OutputStream sslOS = socket.getOutputStream();
        sslOS.write('C');
        sslOS.flush();
        sslIS.read();
        System.out.println("Client: finished");
    } catch (Exception e) {
        throw new RuntimeException("Client: failed.", e);
    }
}
 
Example 21
Source Project: strimzi-kafka-oauth   Source File: OAuthAuthenticator.java    License: Apache License 2.0 5 votes vote down vote up
private static TokenInfo post(URI tokenEndpointUri, SSLSocketFactory socketFactory, HostnameVerifier hostnameVerifier,
                              String authorization, String body, boolean isJwt, PrincipalExtractor principalExtractor) throws IOException {

    long now = System.currentTimeMillis();

    JsonNode result = HttpUtil.post(tokenEndpointUri,
            socketFactory,
            hostnameVerifier,
            authorization,
            "application/x-www-form-urlencoded",
            body,
            JsonNode.class);

    JsonNode token = result.get("access_token");
    if (token == null) {
        throw new IllegalStateException("Invalid response from authorization server: no access_token");
    }

    JsonNode expiresIn = result.get("expires_in");
    if (expiresIn == null) {
        throw new IllegalStateException("Invalid response from authorization server: no expires_in");
    }

    // Some OAuth2 authorization servers don't provide scope in this level,
    // therefore we don't need to make it mandatory
    JsonNode scope = result.get("scope");

    if (isJwt) {
        // try introspect token
        try {
            return introspectAccessToken(token.asText(), principalExtractor);
        } catch (Exception e) {
            log.debug("[IGNORED] Could not parse token as JWT access token. Could not extract subject.", e);
        }
    }

    return new TokenInfo(token.asText(), scope != null ? scope.asText() : null, "undefined", now, now + expiresIn.asLong() * 1000L);
}
 
Example 22
Source Project: IoTgo_Android_App   Source File: Address.java    License: MIT License 5 votes vote down vote up
public Address(String uriHost, int uriPort, SSLSocketFactory sslSocketFactory,
    HostnameVerifier hostnameVerifier, OkAuthenticator authenticator, Proxy proxy,
    List<String> transports) throws UnknownHostException {
  if (uriHost == null) throw new NullPointerException("uriHost == null");
  if (uriPort <= 0) throw new IllegalArgumentException("uriPort <= 0: " + uriPort);
  if (authenticator == null) throw new IllegalArgumentException("authenticator == null");
  if (transports == null) throw new IllegalArgumentException("transports == null");
  this.proxy = proxy;
  this.uriHost = uriHost;
  this.uriPort = uriPort;
  this.sslSocketFactory = sslSocketFactory;
  this.hostnameVerifier = hostnameVerifier;
  this.authenticator = authenticator;
  this.transports = Util.immutableList(transports);
}
 
Example 23
Source Project: TrustKit-Android   Source File: SSLSocketFactoryTest.java    License: MIT License 5 votes vote down vote up
@Test
public void testPinnedDomainWrongHostnameChain() throws IOException {
    // Initialize TrustKit
    String serverHostname = "wrong.host.badssl.com";
    TestableTrustKit.initializeWithNetworkSecurityConfiguration(
            InstrumentationRegistry.getInstrumentation().getContext(), mockReporter);

    // Create a TrustKit SocketFactory and ensure the connection fails
    SSLSocketFactory test = TestableTrustKit.getInstance().getSSLSocketFactory(serverHostname);
    boolean didReceiveHandshakeError = false;
    try {
        test.createSocket(serverHostname, 443).getInputStream();
    } catch (SSLHandshakeException e) {
        if ((e.getCause() instanceof CertificateException
                && !(e.getCause().getMessage().startsWith("Pin verification failed")))) {
            didReceiveHandshakeError = true;
        }
    }
    assertTrue(didReceiveHandshakeError);

    if (Build.VERSION.SDK_INT < 17) {
        // TrustKit does not do anything for API level < 17 hence there is no reporting
        return;
    }

    // Ensure the background reporter was called
    verify(mockReporter).pinValidationFailed(
            eq(serverHostname),
            eq(0),
            (List<X509Certificate>) org.mockito.Matchers.isNotNull(),
            (List<X509Certificate>) org.mockito.Matchers.isNotNull(),
            eq(TestableTrustKit.getInstance().getConfiguration().getPolicyForHostname(serverHostname)),
            eq(PinningValidationResult.FAILED_CERTIFICATE_CHAIN_NOT_TRUSTED)
    );
}
 
Example 24
Source Project: collect-earth   Source File: PlanetImagery.java    License: MIT License 5 votes vote down vote up
private static SSLSocketFactory getSSLAcceptAllFactory(){
	SSLSocketFactory factory = null;
	try {
		Security.getProviders();
		final SSLContext ssl = SSLContext.getInstance("TLSv1");
		ssl.init(null, new TrustManager[] { new TrustAllCertificates() }, null);
		return ssl.getSocketFactory();
	} catch (Exception e) {
		logger.error( "Error obtaining SSL factory when opeining Planet REST URL",e);
	}
	
	return factory;
}
 
Example 25
Source Project: okta-sdk-appauth-android   Source File: TestUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static SSLSocketFactory getSSL(Object object) {
    try {
        /*
        * To generate keystore you should use next command
        * keytool -genkey -v -keystore mock.keystore.jks -alias okta_android_sdk -keyalg RSA -keysize 2048 -validity 10000
        * Copy mock.keystore.jks in folder library/src/test/resources
        * */
        URL filepath = object.getClass().getClassLoader().getResource("mock.keystore.jks");
        File file = new File(filepath.getPath());

        FileInputStream stream = new FileInputStream(file);
        char[] serverKeyStorePassword = "123456".toCharArray();
        KeyStore serverKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        serverKeyStore.load(stream, serverKeyStorePassword);

        String kmfAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(kmfAlgorithm);
        kmf.init(serverKeyStore, serverKeyStorePassword);

        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(kmfAlgorithm);
        trustManagerFactory.init(serverKeyStore);

        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(kmf.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
        return sslContext.getSocketFactory();
    } catch (Exception e) {
        return null;
    }
}
 
Example 26
Source Project: j2objc   Source File: HandshakeCompletedEventTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @throws IOException
 * javax.net.ssl.HandshakeCompletedEvent#getLocalCertificates()
 */
public final void test_getLocalCertificates() throws Exception {
    mySSLSession session = new mySSLSession("localhost", 1080, null);
    SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
    HandshakeCompletedEvent event = new HandshakeCompletedEvent(socket, session);
    assertNull(event.getLocalCertificates());
}
 
Example 27
Source Project: java-cloudant   Source File: SslAuthenticationTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Assert that building a client with SSL Authentication disabled first, then setting
 * a custom SSL factory will throw an IllegalStateException.
 */
@TestTemplate
public void testSSLAuthDisabledWithCustomSSLFactory() {
    assertThrows(IllegalStateException.class, new Executable() {
        @Override
        public void execute() throws Throwable {

            CloudantClient dbClient = CloudantClientHelper.getClientBuilder()
                    .disableSSLAuthentication()
                    .customSSLSocketFactory((SSLSocketFactory) SSLSocketFactory.getDefault())
                    .build();
        }
    });
}
 
Example 28
Source Project: rapidoid   Source File: NetUtil.java    License: Apache License 2.0 5 votes vote down vote up
private static SSLSocket sslSocket(String address, int port, int timeout) throws Exception {
	SSLContext sc = TLSUtil.createTrustingContext();
	SSLSocketFactory ssf = sc.getSocketFactory();
	SSLSocket socket = (SSLSocket) ssf.createSocket(address, port);
	socket.setSoTimeout(timeout);
	socket.startHandshake();
	return socket;
}
 
Example 29
Source Project: wildfly-openssl   Source File: BasicOpenSSLEngineTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSingleEnabledProtocol() throws IOException, InterruptedException {
    final String[] protocols = new String[] { "TLSv1", "TLSv1.1", "TLSv1.2" };
    for (String protocol : protocols) {
        try (ServerSocket serverSocket = SSLTestUtils.createServerSocket()) {
            final AtomicReference<byte[]> sessionID = new AtomicReference<>();
            final SSLContext sslContext = SSLTestUtils.createSSLContext("openssl.TLS");
            final AtomicReference<SSLEngine> engineRef = new AtomicReference<>();

            EchoRunnable echo = new EchoRunnable(serverSocket, sslContext, sessionID, (engine -> {
                engineRef.set(engine);
                try {
                    engine.setEnabledProtocols(new String[]{ protocol }); // only one protocol enabled on server side
                    return engine;
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }));
            Thread acceptThread = new Thread(echo);
            acceptThread.start();
            final SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
            socket.connect(SSLTestUtils.createSocketAddress());
            socket.getOutputStream().write(MESSAGE.getBytes(StandardCharsets.US_ASCII));
            byte[] data = new byte[100];
            int read = socket.getInputStream().read(data);

            Assert.assertEquals(MESSAGE, new String(data, 0, read));
            Assert.assertArrayEquals(socket.getSession().getId(), sessionID.get());
            Assert.assertEquals(protocol, socket.getSession().getProtocol());
            Assert.assertArrayEquals(new String[]{ SSL_PROTO_SSLv2Hello, protocol }, engineRef.get().getEnabledProtocols());
            socket.getSession().invalidate();
            socket.close();
            serverSocket.close();
            acceptThread.join();
        }
    }
}
 
Example 30
Source Project: xipki   Source File: ScepClient.java    License: Apache License 2.0 5 votes vote down vote up
public ScepClient(CaIdentifier caId, CaCertValidator caCertValidator,
    SSLSocketFactory sslSocketFactory, HostnameVerifier hostnameVerifier)
    throws MalformedURLException {
  super(caId, caCertValidator);
  this.sslSocketFactory = sslSocketFactory;
  this.hostnameVerifier = hostnameVerifier;
}