javax.net.ssl.SSLSocketFactory Java Examples

The following examples show how to use javax.net.ssl.SSLSocketFactory. 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: Client.java    From jdk9-jigsaw with 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
Source File: SSLTest.java    From ssltest with 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 #3
Source File: SslRMIServerSocketFactory.java    From JDKSourceCode1.8 with 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 #4
Source File: MainActivity.java    From developerWorks with 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 #5
Source File: SocketFactorySettings.java    From nv-websocket-client with 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 #6
Source File: SSLCertificateSocketFactory.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
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 #7
Source File: SslRMIServerSocketFactory.java    From hottub 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 #8
Source File: ConnectorBootstrap.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
@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 #9
Source File: TokenStreamProvider.java    From jgroups-kubernetes with 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 #10
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 #11
Source File: OkHttpTlsUpgrader.java    From grpc-nebula-java with 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 #12
Source File: SSLSocketFactoryTest.java    From TrustKit-Android with 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 File: OkHttpClientExample.java    From http2-examples with 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 #14
Source File: Utils.java    From carbon-device-mgt with 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 #15
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 #16
Source File: RemoteBlockStreamHandle.java    From ghidra with 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 #17
Source File: OkHttpClientTransport.java    From grpc-nebula-java with 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 #18
Source File: SSLPinGenerator.java    From ssl-pin-generator with MIT License 5 votes vote down vote up
private void fetchAndPrintPinHashs() throws Exception {
	System.out.println("**Run this on a trusted network**\nGenerating SSL pins for: " + hostname);
	SSLContext context = SSLContext.getInstance("TLS");
	PublicKeyExtractingTrustManager tm = new PublicKeyExtractingTrustManager();
	context.init(null, new TrustManager[] { tm }, null);
	SSLSocketFactory factory = context.getSocketFactory();
	SSLSocket socket = (SSLSocket) factory.createSocket(hostname, hostPort);
	socket.setSoTimeout(10000);
	socket.startHandshake();
	socket.close();
}
 
Example #19
Source File: TLSFallbackSSLSocketTest.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Test
void noHandshakeExceptionNoTLS13() throws IOException {
    SSLSocket sslSocket = mockSocket();
    SSLSocketFactory sslFactory = mock(SSLSocketFactory.class);

    TLSFallbackSSLSocketFactory factory = TLSFallbackSSLSocketFactory.wrapFactory(sslFactory);
    TLSFallbackSSLSocket socket = new TLSFallbackSSLSocket(sslSocket, factory);

    socket.startHandshake();

    verify(sslSocket, never()).setEnabledProtocols(any());
}
 
Example #20
Source File: Fix5070632.java    From TencentKona-8 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 #21
Source File: HttpsUtils.java    From UltimateAndroid with Apache License 2.0 5 votes vote down vote up
/**
 * Build SSLSocketFactory using certificate file from assets.
 *
 * @param context
 * @param certFilePath
 * @return
 */
public static SSLSocketFactory getSSLSocketFactory(Context context, String certFilePath) throws NoSuchAlgorithmException,
        KeyStoreException, KeyManagementException, CertificateException, IOException {

    // Load CAs from an InputStream
    // (could be from a resource or ByteArrayInputStream or ...)
    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    InputStream is = context.getResources().getAssets().open(certFilePath);
    InputStream caInput = new BufferedInputStream(is);
    Certificate ca;
    try {
        ca = cf.generateCertificate(caInput);
        // System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN());
    } finally {
        caInput.close();
    }

    // Create a KeyStore containing our trusted CAs
    String keyStoreType = KeyStore.getDefaultType();
    KeyStore keyStore = KeyStore.getInstance(keyStoreType);
    keyStore.load(null, null);
    keyStore.setCertificateEntry("ca", ca);

    // Create a TrustManager that trusts the CAs in our KeyStore
    String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
    tmf.init(keyStore);

    // Create an SSLContext that uses our TrustManager
    SSLContext contexts = SSLContext.getInstance("TLS");
    contexts.init(null, tmf.getTrustManagers(), null);
    return contexts.getSocketFactory();


}
 
Example #22
Source File: HttpsURLConnection.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Sets the SSL socket factory.
 * @param sf the SSL socket factory
 */
public void setSSLSocketFactory(SSLSocketFactory sf) {
    if (sf == null) {
        throw new IllegalArgumentException(
            "no SSLSocketFactory specified");
    }

    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        sm.checkSetFactory();
    }

    sslSocketFactory = sf;
}
 
Example #23
Source File: HttpEngine.java    From cordova-amazon-fireos with Apache License 2.0 5 votes vote down vote up
/** Connect to the origin server either directly or via a proxy. */
protected final void connect() throws IOException {
  if (connection != null) {
    return;
  }
  if (routeSelector == null) {
    String uriHost = uri.getHost();
    if (uriHost == null) {
      throw new UnknownHostException(uri.toString());
    }
    SSLSocketFactory sslSocketFactory = null;
    HostnameVerifier hostnameVerifier = null;
    if (uri.getScheme().equalsIgnoreCase("https")) {
      sslSocketFactory = client.getSslSocketFactory();
      hostnameVerifier = client.getHostnameVerifier();
    }
    Address address = new Address(uriHost, getEffectivePort(uri), sslSocketFactory,
        hostnameVerifier, client.getAuthenticator(), client.getProxy(), client.getTransports());
    routeSelector = new RouteSelector(address, uri, client.getProxySelector(),
        client.getConnectionPool(), Dns.DEFAULT, client.getRoutesDatabase());
  }
  connection = routeSelector.next(method);
  if (!connection.isConnected()) {
    connection.connect(client.getConnectTimeout(), client.getReadTimeout(), getTunnelConfig());
    client.getConnectionPool().maybeShare(connection);
    client.getRoutesDatabase().connected(connection.getRoute());
  } else if (!connection.isSpdy()) {
      connection.updateReadTimeout(client.getReadTimeout());
  }
  connected(connection);
  if (connection.getRoute().getProxy() != client.getProxy()) {
    // Update the request line if the proxy changed; it may need a host name.
    requestHeaders.getHeaders().setRequestLine(getRequestLine());
  }
}
 
Example #24
Source File: SslUtil.java    From saluki with Apache License 2.0 5 votes vote down vote up
public static SSLSocketFactory newSslSocketFactoryForCa(InputStream certChain) throws Exception {
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(null, null);
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509Certificate cert = (X509Certificate) cf.generateCertificate(new BufferedInputStream(certChain));
    X500Principal principal = cert.getSubjectX500Principal();
    ks.setCertificateEntry(principal.getName("RFC2253"), cert);
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(ks);
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, trustManagerFactory.getTrustManagers(), null);
    return context.getSocketFactory();
}
 
Example #25
Source File: SslContextFactory.java    From nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Convenience method to return the {@link SSLSocketFactory} from the created {@link SSLContext}
 * because that is what most callers of {@link #createSslContext(TlsConfiguration, ClientAuth)}
 * actually need and don't know what to provide for the {@link ClientAuth} parameter.
 *
 * @param tlsConfiguration the TLS configuration container object
 * @return the configured SSLSocketFactory (can be {@code null})
 * @throws TlsException if there is a problem creating the SSLContext or SSLSocketFactory
 */
public static SSLSocketFactory createSSLSocketFactory(TlsConfiguration tlsConfiguration) throws TlsException {
    SSLContext sslContext = createSslContext(tlsConfiguration, ClientAuth.REQUIRED);
    if (sslContext == null) {
        // Only display an error in the log if the provided config wasn't empty
        if (!TlsConfiguration.isEmpty(tlsConfiguration)) {
            logger.error("The SSLContext could not be formed from the provided TLS configuration. Check the provided keystore and truststore properties");
        }
        return null;
    }
    return sslContext.getSocketFactory();
}
 
Example #26
Source File: WebViewCacheWrapper.java    From YCWebView with Apache License 2.0 5 votes vote down vote up
public Builder setSSLSocketFactory(SSLSocketFactory sslSocketFactory, X509TrustManager trustManager) {
    if (sslSocketFactory != null && trustManager != null) {
        mSSLSocketFactory = sslSocketFactory;
        mX509TrustManager = trustManager;
    }
    return this;
}
 
Example #27
Source File: ConfigXml.java    From projectforge-webapp with GNU General Public License v3.0 5 votes vote down vote up
private SSLSocketFactory createSSLSocketFactory(final InputStream is, final String passphrase) throws Exception
{
  final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
  ks.load(is, passphrase.toCharArray());
  is.close();
  final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
  tmf.init(ks);
  final X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
  final SSLContext context = SSLContext.getInstance("TLS");
  context.init(null, new TrustManager[] { defaultTrustManager}, null);
  return context.getSocketFactory();
}
 
Example #28
Source File: WaspBuilderTest.java    From wasp with Apache License 2.0 5 votes vote down vote up
@Test
public void testWaspHttpStackCustom() throws Exception {

  class MyHttpStack implements WaspHttpStack {

    @Override
    public HttpStack getHttpStack() {
      return new OkHttpStack(new OkHttpClient());
    }

    @Override
    public void setHostnameVerifier(HostnameVerifier hostnameVerifier) {

    }

    @Override
    public void setSslSocketFactory(SSLSocketFactory sslSocketFactory) {

    }

    @Override
    public void setCookieHandler(CookieHandler cookieHandler) {

    }
  }

  Wasp.Builder builder = new Wasp.Builder(context)
      .setWaspHttpStack(new MyHttpStack())
      .setEndpoint("http");
  builder.build();

  //default should be NONE
  assertThat(builder.getWaspHttpStack()).isInstanceOf(MyHttpStack.class);
}
 
Example #29
Source File: TapchatModule.java    From tapchat-android with Apache License 2.0 5 votes vote down vote up
@Provides @Singleton public OkHttpClient provideOkHttp(SSLSocketFactory sslSocketFactory,
        HostnameVerifier hostnameVerifier) {

    try {
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.setCache(new Cache(mAppContext.getCacheDir(), MAX_CACHE_SIZE));
        okHttpClient.setHostnameVerifier(hostnameVerifier);
        okHttpClient.setSslSocketFactory(sslSocketFactory);
        return okHttpClient;
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}
 
Example #30
Source File: HttpsSocketFacTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Socket createSocket(Socket s, String host, int port,
                           boolean autoClose) throws IOException {
    socketWrapped = true;
    return ((SSLSocketFactory) SSLSocketFactory.getDefault()).createSocket
                                                       (s, host, port, autoClose);
}