Java Code Examples for javax.net.ssl.SSLSocketFactory

The following are top voted examples for showing how to use javax.net.ssl.SSLSocketFactory. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: GitHub   File: Address.java   View source code 10 votes vote down vote up
public Address(String uriHost, int uriPort, Dns dns, SocketFactory socketFactory,
    SSLSocketFactory sslSocketFactory, HostnameVerifier hostnameVerifier,
    CertificatePinner certificatePinner, Authenticator proxyAuthenticator, Proxy proxy,
    List<Protocol> protocols, List<ConnectionSpec> connectionSpecs, ProxySelector proxySelector) {
  this.url = new HttpUrl.Builder()
      .scheme(sslSocketFactory != null ? "https" : "http")
      .host(uriHost)
      .port(uriPort)
      .build();

  if (dns == null) throw new NullPointerException("dns == null");
  this.dns = dns;

  if (socketFactory == null) throw new NullPointerException("socketFactory == null");
  this.socketFactory = socketFactory;

  if (proxyAuthenticator == null) {
    throw new NullPointerException("proxyAuthenticator == null");
  }
  this.proxyAuthenticator = proxyAuthenticator;

  if (protocols == null) throw new NullPointerException("protocols == null");
  this.protocols = Util.immutableList(protocols);

  if (connectionSpecs == null) throw new NullPointerException("connectionSpecs == null");
  this.connectionSpecs = Util.immutableList(connectionSpecs);

  if (proxySelector == null) throw new NullPointerException("proxySelector == null");
  this.proxySelector = proxySelector;

  this.proxy = proxy;
  this.sslSocketFactory = sslSocketFactory;
  this.hostnameVerifier = hostnameVerifier;
  this.certificatePinner = certificatePinner;
}
 
Example 2
Project: pcloud-networking-java   File: RealConnection.java   View source code 9 votes vote down vote up
RealConnection(SocketFactory socketFactory,
               SSLSocketFactory sslSocketFactory,
               HostnameVerifier hostnameVerifier,
               Endpoint endpoint, int connectTimeout, TimeUnit timeUnit) throws IOException {
    this.socketFactory = socketFactory;
    this.sslSocketFactory = sslSocketFactory;
    this.hostnameVerifier = hostnameVerifier;
    this.endpoint = endpoint;
    try {
        this.rawSocket = createSocket(endpoint, (int) timeUnit.toMillis(connectTimeout));
        this.socket = upgradeSocket(rawSocket, endpoint);
        this.inputStream = socket.getInputStream();
        this.outputStream = socket.getOutputStream();
        this.source = Okio.buffer(Okio.source(inputStream));
        this.sink = Okio.buffer(Okio.sink(outputStream));
        socket.setSoTimeout(0);
        source.timeout().timeout(readTimeout(), TimeUnit.MILLISECONDS);
        sink.timeout().timeout(writeTimeout(), TimeUnit.MILLISECONDS);
        connected = true;
    } finally {
        if (!connected) {
            close();
        }
    }
}
 
Example 3
Project: GitHub   File: Address.java   View source code 8 votes vote down vote up
public Address(String uriHost, int uriPort, Dns dns, SocketFactory socketFactory,
    @Nullable SSLSocketFactory sslSocketFactory, @Nullable HostnameVerifier hostnameVerifier,
    @Nullable CertificatePinner certificatePinner, Authenticator proxyAuthenticator,
    @Nullable Proxy proxy, List<Protocol> protocols, List<ConnectionSpec> connectionSpecs,
    ProxySelector proxySelector) {
  this.url = new HttpUrl.Builder()
      .scheme(sslSocketFactory != null ? "https" : "http")
      .host(uriHost)
      .port(uriPort)
      .build();

  if (dns == null) throw new NullPointerException("dns == null");
  this.dns = dns;

  if (socketFactory == null) throw new NullPointerException("socketFactory == null");
  this.socketFactory = socketFactory;

  if (proxyAuthenticator == null) {
    throw new NullPointerException("proxyAuthenticator == null");
  }
  this.proxyAuthenticator = proxyAuthenticator;

  if (protocols == null) throw new NullPointerException("protocols == null");
  this.protocols = Util.immutableList(protocols);

  if (connectionSpecs == null) throw new NullPointerException("connectionSpecs == null");
  this.connectionSpecs = Util.immutableList(connectionSpecs);

  if (proxySelector == null) throw new NullPointerException("proxySelector == null");
  this.proxySelector = proxySelector;

  this.proxy = proxy;
  this.sslSocketFactory = sslSocketFactory;
  this.hostnameVerifier = hostnameVerifier;
  this.certificatePinner = certificatePinner;
}
 
Example 4
Project: JCurl   File: JCurl.java   View source code 7 votes vote down vote up
/**
 * Get an instance of JCurl with options configured by the {@link #Builder()}.
 * @return
 */
public JCurl build() {
  instance.expectedResponseSet.add(200);

  setSystemProperty("javax.net.ssl.keyStore", instance.keyStore);
  setSystemProperty("javax.net.ssl.keyStoreType", instance.storeType);
  setSystemProperty("javax.net.ssl.keyStorePassword", instance.storePass);
  setSystemProperty("javax.net.ssl.trustStore", instance.trustStore);
  setSystemProperty("javax.net.ssl.trustStoreType", instance.trustType);
  setSystemProperty("javax.net.ssl.trustStorePassword", instance.trustPass);
  setSystemProperty("http.proxyHost", instance.httpProxyHost);
  setSystemProperty("http.proxyPort", instance.httpProxyPort);
  setSystemProperty("https.proxyHost", instance.httpsProxyHost);
  setSystemProperty("https.proxyPort", instance.httpsProxyPort);
  setSystemProperty("https.nonProxyHosts", instance.nonProxyHosts);

  if (instance.verbosity >= 3) {
    System.setProperty("javax.net.debug", "ssl");
  }

  HttpsURLConnection.setDefaultSSLSocketFactory((SSLSocketFactory) SSLSocketFactory.getDefault());

  initSSLContext();

  return instance;
}
 
Example 5
Project: jdk8u-jdk   File: ConnectorBootstrap.java   View source code 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 6
Project: PeSanKita-lib   File: WebSocketConnection.java   View source code 6 votes vote down vote up
public synchronized void connect() {
  Log.w(TAG, "WSC connect()...");

  if (client == null) {
    String                                   filledUri     = String.format(wsUri, credentialsProvider.getUser(), credentialsProvider.getPassword());
    Pair<SSLSocketFactory, X509TrustManager> socketFactory = createTlsSocketFactory(trustStore);

    OkHttpClient okHttpClient = new OkHttpClient.Builder()
                                                .sslSocketFactory(socketFactory.first(), socketFactory.second())
                                                .readTimeout(KEEPALIVE_TIMEOUT_SECONDS + 10, TimeUnit.SECONDS)
                                                .connectTimeout(KEEPALIVE_TIMEOUT_SECONDS + 10, TimeUnit.SECONDS)
                                                .build();

    Request.Builder requestBuilder = new Request.Builder().url(filledUri);

    if (userAgent != null) {
      requestBuilder.addHeader("X-Signal-Agent", userAgent);
    }

    this.connected = false;
    this.client    = okHttpClient.newWebSocket(requestBuilder.build(), this);
  }
}
 
Example 7
Project: GitHub   File: ConnectionSpecTest.java   View source code 6 votes vote down vote up
@Test public void tls_missingTlsVersion() throws Exception {
  ConnectionSpec tlsSpec = new ConnectionSpec.Builder(true)
      .cipherSuites(CipherSuite.TLS_RSA_WITH_RC4_128_MD5)
      .tlsVersions(TlsVersion.TLS_1_2)
      .supportsTlsExtensions(false)
      .build();

  SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
  socket.setEnabledCipherSuites(new String[] {
      CipherSuite.TLS_RSA_WITH_RC4_128_MD5.javaName,
  });

  socket.setEnabledProtocols(
      new String[] {TlsVersion.TLS_1_2.javaName, TlsVersion.TLS_1_1.javaName});
  assertTrue(tlsSpec.isCompatible(socket));

  socket.setEnabledProtocols(new String[] {TlsVersion.TLS_1_1.javaName});
  assertFalse(tlsSpec.isCompatible(socket));
}
 
Example 8
Project: JAVA-   File: HTTPSCoder.java   View source code 6 votes vote down vote up
/**
 * 获得SSLSocektFactory
 * 
 * @param password 密码
 * @param keyStorePath 密钥库路径
 * @param trustStorePath 信任库路径
 * @return SSLSocketFactory
 * @throws Exception
 */
private static SSLSocketFactory getSSLSocketFactory(String password, String keyStorePath, String trustStorePath)
		throws Exception {
	// 实例化密钥库
	KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
	// 获得密钥库
	KeyStore keyStore = getKeyStore(keyStorePath, password);
	// 初始化密钥工厂
	keyManagerFactory.init(keyStore, password.toCharArray());
	// 实例化信任库
	TrustManagerFactory trustManagerFactory = TrustManagerFactory
			.getInstance(TrustManagerFactory.getDefaultAlgorithm());
	// 获得信任库
	KeyStore trustStore = getKeyStore(trustStorePath, password);
	// 初始化信任库
	trustManagerFactory.init(trustStore);
	// 实例化SSL上下文
	SSLContext ctx = SSLContext.getInstance(PROTOCOL);
	// 初始化SSL上下文
	ctx.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
	// 获得SSLSocketFactory
	return ctx.getSocketFactory();

}
 
Example 9
Project: parabuild-ci   File: HsqlSocketFactorySecure.java   View source code 6 votes vote down vote up
/**
 * Retrieves the underlying javax.net.ssl.SSLSocketFactory.
 *
 * @throws Exception if there is a problem retrieving the
 *      underlying factory
 * @return the underlying javax.net.ssl.SSLSocketFactory
 */
protected SSLSocketFactory getSocketFactoryImpl() throws Exception {

    Object factory;

    synchronized (socket_factory_mutex) {
        factory = socketFactory;

        if (factory == null) {
            factory       = SSLSocketFactory.getDefault();
            socketFactory = factory;
        }
    }

    return (SSLSocketFactory) factory;
}
 
Example 10
Project: intellij-mattermost-plugin   File: MattermostClient.java   View source code 6 votes vote down vote up
private SSLSocketFactory createSslSocketFactory() throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException, KeyManagementException {
    // load up the key store
    String STORETYPE = "JKS";
    String KEYSTORE = "keystore.jks";
    String STOREPASSWORD = "storepassword";
    String KEYPASSWORD = "keypassword";

    KeyStore ks = KeyStore.getInstance(STORETYPE);
    ks.load(MattermostClient.class.getResourceAsStream(KEYSTORE), STOREPASSWORD.toCharArray());

    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
    kmf.init(ks, KEYPASSWORD.toCharArray());
    TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
    tmf.init(ks);

    SSLContext sslContext = null;
    sslContext = SSLContext.getInstance("TLS");
    //		sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    sslContext.init(null, null, null); // will use java's default key and trust store which is sufficient unless you deal with self-signed certificates

    return sslContext.getSocketFactory();// (SSLSocketFactory) SSLSocketFactory.getDefault();
}
 
Example 11
Project: JRediClients   File: JedisPool.java   View source code 6 votes vote down vote up
public JedisPool(final String host, final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters,
		final HostnameVerifier hostnameVerifier) {
	URI uri = URI.create(host);
	if (JedisURIHelper.isValid(uri)) {
		String h = uri.getHost();
		int port = uri.getPort();
		String password = JedisURIHelper.getPassword(uri);
		int database = JedisURIHelper.getDBIndex(uri);
		boolean ssl = uri.getScheme().equals("rediss");
		this.internalPool = new GenericObjectPool<Jedis>(
				new JedisFactory(h, port, Protocol.DEFAULT_TIMEOUT, Protocol.DEFAULT_TIMEOUT, password, database,
						null, ssl, sslSocketFactory, sslParameters, hostnameVerifier),
				new GenericObjectPoolConfig());
	} else {
		this.internalPool = new GenericObjectPool<Jedis>(
				new JedisFactory(host, Protocol.DEFAULT_PORT, Protocol.DEFAULT_TIMEOUT, Protocol.DEFAULT_TIMEOUT,
						null, Protocol.DEFAULT_DATABASE, null, false, null, null, null),
				new GenericObjectPoolConfig());
	}
}
 
Example 12
Project: iBase4J   File: HTTPSPKCSCoder.java   View source code 6 votes vote down vote up
/**
 * 获得SSLSocektFactory
 * 
 * @param password 密码
 * @param keyStorePath 密钥库路径
 * @param trustStorePath 信任库路径
 * @return SSLSocketFactory
 * @throws Exception
 */
private static SSLSocketFactory getSSLSocketFactory(String password, String keyStorePath, String trustStorePath)
		throws Exception {
	// 实例化密钥库
	KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
	// 获得密钥库
	KeyStore keyStore = getKeyStore(keyStorePath, password);
	// 初始化密钥工厂
	keyManagerFactory.init(keyStore, password.toCharArray());
	// 实例化信任库
	TrustManagerFactory trustManagerFactory = TrustManagerFactory
			.getInstance(TrustManagerFactory.getDefaultAlgorithm());
	// 获得信任库
	KeyStore trustStore = getKeyStore(trustStorePath, password);
	// 初始化信任库
	trustManagerFactory.init(trustStore);
	// 实例化SSL上下文
	SSLContext ctx = SSLContext.getInstance(PROTOCOL);
	// 初始化SSL上下文
	ctx.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
	// 获得SSLSocketFactory
	return ctx.getSocketFactory();

}
 
Example 13
Project: GitHub   File: ConnectionSpecTest.java   View source code 6 votes vote down vote up
@Test public void tls_missingTlsVersion() throws Exception {
  ConnectionSpec tlsSpec = new ConnectionSpec.Builder(true)
      .cipherSuites(CipherSuite.TLS_RSA_WITH_RC4_128_MD5)
      .tlsVersions(TlsVersion.TLS_1_2)
      .supportsTlsExtensions(false)
      .build();

  SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
  socket.setEnabledCipherSuites(new String[] {
      CipherSuite.TLS_RSA_WITH_RC4_128_MD5.javaName,
  });

  socket.setEnabledProtocols(
      new String[] {TlsVersion.TLS_1_2.javaName, TlsVersion.TLS_1_1.javaName});
  assertTrue(tlsSpec.isCompatible(socket));

  socket.setEnabledProtocols(new String[] {TlsVersion.TLS_1_1.javaName});
  assertFalse(tlsSpec.isCompatible(socket));
}
 
Example 14
Project: JRediClients   File: JedisClusterInfoCache.java   View source code 6 votes vote down vote up
public JedisPool setupNodeIfNotExist(HostAndPort node, boolean ssl, SSLSocketFactory sslSocketFactory,
		SSLParameters sslParameters, HostnameVerifier hostnameVerifier) {
	w.lock();
	try {
		String nodeKey = getNodeKey(node);
		JedisPool existingPool = nodes.get(nodeKey);
		if (existingPool != null)
			return existingPool;

		JedisPool nodePool = new JedisPool(poolConfig, node.getHost(), node.getPort(), connectionTimeout, soTimeout,
				password, 0, null, ssl, sslSocketFactory, sslParameters, hostnameVerifier);
		nodes.put(nodeKey, nodePool);
		return nodePool;
	} finally {
		w.unlock();
	}
}
 
Example 15
Project: cornerstone   File: SecurityUtil.java   View source code 5 votes vote down vote up
public static SSLSocketFactory getSSLSocketFactory () throws KeyManagementException, NoSuchProviderException, NoSuchAlgorithmException {

        if(VISSLFACTORY == null) {
            TrustManager[] tm = {new MyX509TrustManager()};
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new SecureRandom());
            VISSLFACTORY = sslContext.getSocketFactory();
        }
        return VISSLFACTORY;
    }
 
Example 16
Project: lemon   File: CdnUtils.java   View source code 5 votes vote down vote up
public static void configHttps(HttpURLConnection conn) throws Exception {
    TrustManager[] tm = { new TrustAllX509TrustManager() };
    SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");

    sslContext.init(null, tm, new java.security.SecureRandom());

    SSLSocketFactory ssf = sslContext.getSocketFactory();

    // ssf.setHostnameVerifier(new TrustAllHostnameVerifier());
    ((HttpsURLConnection) conn).setSSLSocketFactory(ssf);
    ((HttpsURLConnection) conn)
            .setHostnameVerifier(new TrustAllHostnameVerifier());
}
 
Example 17
Project: jdk8u-jdk   File: HttpsURLConnection.java   View source code 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 18
Project: super-volley   File: ClientSSLSocketFactory.java   View source code 5 votes vote down vote up
static SSLSocketFactory getSocketFactory() {
    if (socketFactory == null) {
        try {
            X509TrustManager trustManager = get509TrustManager();
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, new TrustManager[]{trustManager}, null);
            socketFactory = sslContext.getSocketFactory();
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            VolleyLog.e(TAG, "Unable to create the ssl socket factory.");
            return SSLCertificateSocketFactory.getDefault(0, null);
        }
    }
    return socketFactory;
}
 
Example 19
Project: Tusky   File: OkHttpUtils.java   View source code 5 votes vote down vote up
private static OkHttpClient.Builder enableHigherTlsOnPreLollipop(OkHttpClient.Builder builder) {
    if (Build.VERSION.SDK_INT >= 16 && Build.VERSION.SDK_INT < 22) {
        try {
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(
                    TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init((KeyStore) null);
            TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
            if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
                throw new IllegalStateException("Unexpected default trust managers:"
                        + Arrays.toString(trustManagers));
            }

            X509TrustManager trustManager = (X509TrustManager) trustManagers[0];

            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, new TrustManager[] { trustManager }, null);
            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

            builder.sslSocketFactory(new SSLSocketFactoryCompat(sslSocketFactory),
                    trustManager);
        } catch (NoSuchAlgorithmException|KeyStoreException|KeyManagementException e) {
            Log.e(TAG, "Failed enabling TLS 1.1 & 1.2. " + e.getMessage());
        }
    }

    return builder;
}
 
Example 20
Project: lighthouse   File: DefaultHttpClientConnectionFactory.java   View source code 5 votes vote down vote up
@Override
public HttpClientConnection openConnection(URL url) throws IOException {
    Socket socket = "https".equalsIgnoreCase(url.getProtocol())
            ? SSLSocketFactory.getDefault().createSocket(url.getHost(), url.getPort() > 0 ? url.getPort() : 443)
            : new Socket(url.getHost(), url.getPort() > 0 ? url.getPort() : 80);

    return DefaultBHttpClientConnectionFactory.INSTANCE.createConnection(socket);
}
 
Example 21
Project: bubichain-sdk-java   File: HttpKit.java   View source code 5 votes vote down vote up
/**
 *  鍙戦�丳ost璇锋眰
 * @param url
 * @param params
 * @return
 * @throws IOException 
 * @throws NoSuchProviderException 
 * @throws NoSuchAlgorithmException 
 * @throws KeyManagementException 
 */
public static String post(String url, String params,Boolean https) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
	StringBuffer bufferRes = null;
    TrustManager[] tm = { new MyX509TrustManager() };
    SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
    sslContext.init(null, tm, new java.security.SecureRandom());
    // 浠庝笂杩癝SLContext瀵硅薄涓緱鍒癝SLSocketFactory瀵硅薄  
    SSLSocketFactory ssf = sslContext.getSocketFactory();

    URL urlGet = new URL(url);
    HttpsURLConnection http = (HttpsURLConnection) urlGet.openConnection();
    // 杩炴帴瓒呮椂
    http.setConnectTimeout(50000);
    // 璇诲彇瓒呮椂 --鏈嶅姟鍣ㄥ搷搴旀瘮杈冩參锛屽澶ф椂闂�
    http.setReadTimeout(50000);
    http.setRequestMethod("POST");
    http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
    http.setSSLSocketFactory(ssf);
    http.setHostnameVerifier(new Verifier());
    http.setDoOutput(true);
    http.setDoInput(true);
    http.connect();

    OutputStream out = http.getOutputStream();
    out.write(params.getBytes("UTF-8"));
    out.flush();
    out.close();

    InputStream in = http.getInputStream();
    BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
    String valueString = null;
    bufferRes = new StringBuffer();
    while ((valueString = read.readLine()) != null){
        bufferRes.append(valueString);
    }
    in.close();
    if (http != null) {
        // 鍏抽棴杩炴帴
        http.disconnect();
    }
    return bufferRes.toString();
}
 
Example 22
Project: openjdk-jdk10   File: StartTlsResponseImpl.java   View source code 5 votes vote down vote up
private SSLSocketFactory getDefaultFactory() throws IOException {

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

        return (defaultFactory =
            (SSLSocketFactory) SSLSocketFactory.getDefault());
    }
 
Example 23
Project: DNASDKJava   File: RestHttp.java   View source code 5 votes vote down vote up
/**
 * Get请求
 * 
 * @param url
 * @param https
 * @return
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws IOException
 * @throws KeyManagementException
 */
private static String get(String url /*,String body*/ ,boolean https) throws NoSuchAlgorithmException, NoSuchProviderException, IOException, KeyManagementException {
	// 创建链接
	URL u = new URL(url);
    HttpURLConnection http = (HttpURLConnection) u.openConnection();
    // 连接超时
    http.setConnectTimeout(50000);
    http.setReadTimeout(50000);
    http.setRequestMethod("GET");
    http.setRequestProperty("Content-Type","application/json");
    if(https) {
        SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
        sslContext.init(null, new TrustManager[]{new MyX509TrustManager()}, new SecureRandom());
        SSLSocketFactory ssf = sslContext.getSocketFactory();
        ((HttpsURLConnection)http).setSSLSocketFactory(ssf);
    }
    http.setDoOutput(true);
    http.setDoInput(true);
    http.connect();
    // 获取返回
    StringBuilder sb = new StringBuilder();
    try (InputStream is = http.getInputStream()) {
    	try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, DEFAULT_CHARSET))) {
    		String str = null;
    		while((str = reader.readLine()) != null) {
    			sb.append(str);str = null;
    		}
    	}
    }
    // 关闭链接
    if (http != null) {
        http.disconnect();
    }
    return sb.toString();
}
 
Example 24
Project: GitHub   File: Platform.java   View source code 5 votes vote down vote up
public X509TrustManager trustManager(SSLSocketFactory sslSocketFactory) {
  // Attempt to get the trust manager from an OpenJDK socket factory. We attempt this on all
  // platforms in order to support Robolectric, which mixes classes from both Android and the
  // Oracle JDK. Note that we don't support HTTP/2 or other nice features on Robolectric.
  try {
    Class<?> sslContextClass = Class.forName("sun.security.ssl.SSLContextImpl");
    Object context = readFieldOrNull(sslSocketFactory, sslContextClass, "context");
    if (context == null) return null;
    return readFieldOrNull(context, X509TrustManager.class, "trustManager");
  } catch (ClassNotFoundException e) {
    return null;
  }
}
 
Example 25
Project: openjdk-jdk10   File: UnboundSSLUtils.java   View source code 5 votes vote down vote up
static SSLClient init(String host, int port, String cipherSuiteFilter,
        String sniHostName) throws NoSuchAlgorithmException, IOException {
    SSLContext sslContext = SSLContext.getDefault();
    SSLSocketFactory ssf = (SSLSocketFactory) sslContext.getSocketFactory();
    SSLSocket socket = (SSLSocket) ssf.createSocket(host, port);
    SSLParameters params = new SSLParameters();

    if (cipherSuiteFilter != null) {
        String[] cipherSuites = UnboundSSLUtils.filterStringArray(
                ssf.getSupportedCipherSuites(), cipherSuiteFilter);
        System.out.println("Client: enabled cipher suites: "
                + Arrays.toString(cipherSuites));
        params.setCipherSuites(cipherSuites);
    }

    if (sniHostName != null) {
        System.out.println("Client: set SNI hostname: " + sniHostName);
        SNIHostName serverName = new SNIHostName(sniHostName);
        List<SNIServerName> serverNames = new ArrayList<>();
        serverNames.add(serverName);
        params.setServerNames(serverNames);
    }

    socket.setSSLParameters(params);

    return new SSLClient(socket);
}
 
Example 26
Project: qonduit   File: TwoWaySSLFailureIT.java   View source code 5 votes vote down vote up
protected SSLSocketFactory getSSLSocketFactory() throws Exception {
    SslContextBuilder builder = SslContextBuilder.forClient();
    builder.applicationProtocolConfig(ApplicationProtocolConfig.DISABLED);
    // Use server cert / key on client side
    builder.keyManager(serverCert.key(), (String) null, serverCert.cert());
    builder.sslProvider(SslProvider.JDK);
    builder.trustManager(clientTrustStoreFile); // Trust the server cert
    SslContext ctx = builder.build();
    Assert.assertEquals(JdkSslClientContext.class, ctx.getClass());
    JdkSslContext jdk = (JdkSslContext) ctx;
    SSLContext jdkSslContext = jdk.context();
    return jdkSslContext.getSocketFactory();
}
 
Example 27
Project: GitHub   File: ConnectionSpecTest.java   View source code 5 votes vote down vote up
@Test public void tls_defaultCiphers_withFallbackIndicator() throws Exception {
  ConnectionSpec tlsSpec = new ConnectionSpec.Builder(true)
      .tlsVersions(TlsVersion.TLS_1_2)
      .supportsTlsExtensions(false)
      .build();

  SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
  socket.setEnabledCipherSuites(new String[] {
      CipherSuite.TLS_RSA_WITH_RC4_128_MD5.javaName,
      CipherSuite.TLS_RSA_WITH_RC4_128_SHA.javaName,
  });
  socket.setEnabledProtocols(new String[] {
      TlsVersion.TLS_1_2.javaName,
      TlsVersion.TLS_1_1.javaName,
  });

  assertTrue(tlsSpec.isCompatible(socket));
  tlsSpec.apply(socket, true /* isFallback */);

  assertEquals(set(TlsVersion.TLS_1_2.javaName), set(socket.getEnabledProtocols()));

  Set<String> expectedCipherSet =
      set(
          CipherSuite.TLS_RSA_WITH_RC4_128_MD5.javaName,
          CipherSuite.TLS_RSA_WITH_RC4_128_SHA.javaName);
  if (Arrays.asList(socket.getSupportedCipherSuites()).contains("TLS_FALLBACK_SCSV")) {
    expectedCipherSet.add("TLS_FALLBACK_SCSV");
  }
  assertEquals(expectedCipherSet, expectedCipherSet);
}
 
Example 28
Project: BiglyBT   File: SESecurityManagerImpl.java   View source code 5 votes vote down vote up
@Override
public SSLSocketFactory
installServerCertificate(
	URL		url )
{
	return( SESecurityManager.installServerCertificates( url ));
}
 
Example 29
Project: android-util2   File: HttpsHelper.java   View source code 5 votes vote down vote up
/**
     * create ssl socket factory. by target crt file.
     * @param context the context.
     * @param assetsFilePath the crt file path in assets.
     * @return an instance of SSLSocketFactory.
     */
    public static SSLSocketFactory createSSLSocketFactory(Context context, String assetsFilePath) {
        SSLContext sslContext = null;
        try {
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            InputStream certificates = new BufferedInputStream(context.getAssets().open(assetsFilePath));
            Certificate ca;
            try {
                ca = certificateFactory.generateCertificate(certificates);
                System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN());
            } finally {
                certificates.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 = SSLContext.getInstance("TLSv1", "AndroidOpenSSL");
//            sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, tmf.getTrustManagers(), null);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return sslContext != null ? sslContext.getSocketFactory() : null;
    }
 
Example 30
Project: GitHub   File: ClientAuthTest.java   View source code 5 votes vote down vote up
@Test public void clientAuthSkippedForNone() throws Exception {
  OkHttpClient client = buildClient(clientCert, clientIntermediateCa);

  SSLSocketFactory socketFactory = buildServerSslSocketFactory(ClientAuth.NONE);

  server.useHttps(socketFactory, false);
  server.enqueue(new MockResponse().setBody("abc"));

  Call call = client.newCall(new Request.Builder().url(server.url("/")).build());
  Response response = call.execute();
  assertEquals(new X500Principal("CN=localhost"), response.handshake().peerPrincipal());
  assertEquals(null, response.handshake().localPrincipal());
  assertEquals("abc", response.body().string());
}
 
Example 31
Project: okwallet   File: RequestWalletBalanceTask.java   View source code 5 votes vote down vote up
private SSLSocketFactory sslTrustAllCertificates() {
    try {
        final SSLContext context = SSLContext.getInstance("SSL");
        context.init(null, new TrustManager[] { TRUST_ALL_CERTIFICATES }, null);
        final SSLSocketFactory socketFactory = context.getSocketFactory();
        return socketFactory;
    } catch (final Exception x) {
        throw new RuntimeException(x);
    }
}
 
Example 32
Project: GitHub   File: SocketRecorder.java   View source code 5 votes vote down vote up
/** Returns an SSLSocketFactory whose sockets will record all transmitted bytes. */
public SSLSocketFactory sslSocketFactory(SSLSocketFactory delegate) {
  return new DelegatingSSLSocketFactory(delegate) {
    @Override protected SSLSocket configureSocket(SSLSocket sslSocket) throws IOException {
      RecordedSocket recordedSocket = new RecordedSocket();
      recordedSockets.add(recordedSocket);
      return new RecordingSSLSocket(sslSocket, recordedSocket);
    }
  };
}
 
Example 33
Project: GitHub   File: URLConnectionTest.java   View source code 5 votes vote down vote up
private void connectViaHttpsReusingConnections(boolean rebuildClient) throws Exception {
  server.useHttps(sslClient.socketFactory, false);
  server.enqueue(new MockResponse().setBody("this response comes via HTTPS"));
  server.enqueue(new MockResponse().setBody("another response via HTTPS"));

  // The pool will only reuse sockets if the SSL socket factories are the same.
  SSLSocketFactory clientSocketFactory = sslClient.socketFactory;
  RecordingHostnameVerifier hostnameVerifier = new RecordingHostnameVerifier();

  CookieJar cookieJar = new JavaNetCookieJar(new CookieManager());
  ConnectionPool connectionPool = new ConnectionPool();

  urlFactory.setClient(new OkHttpClient.Builder()
      .cache(cache)
      .connectionPool(connectionPool)
      .cookieJar(cookieJar)
      .sslSocketFactory(clientSocketFactory, sslClient.trustManager)
      .hostnameVerifier(hostnameVerifier)
      .build());
  connection = urlFactory.open(server.url("/").url());
  assertContent("this response comes via HTTPS", connection);

  if (rebuildClient) {
    urlFactory.setClient(new OkHttpClient.Builder()
        .cache(cache)
        .connectionPool(connectionPool)
        .cookieJar(cookieJar)
        .sslSocketFactory(clientSocketFactory, sslClient.trustManager)
        .hostnameVerifier(hostnameVerifier)
        .build());
  }

  connection = urlFactory.open(server.url("/").url());
  assertContent("another response via HTTPS", connection);

  assertEquals(0, server.takeRequest().getSequenceNumber());
  assertEquals(1, server.takeRequest().getSequenceNumber());
}
 
Example 34
Project: Tusky   File: OkHttpUtils.java   View source code 5 votes vote down vote up
/**
 * Android version Nougat has a regression where elliptic curve cipher suites are supported, but
 * only the curve secp256r1 is allowed. So, first it's best to just disable all elliptic
 * ciphers, try the connection, and fall back to the all cipher suites enabled list after.
 */
private static void addNougatFixConnectionSpec(List<ConnectionSpec> specList) {
    if (Build.VERSION.SDK_INT != Build.VERSION_CODES.N) {
        return;
    }
    SSLSocketFactory socketFactory;
    try {
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(
                TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init((KeyStore) null);
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
        if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
            throw new IllegalStateException("Unexpected default trust managers:"
                    + Arrays.toString(trustManagers));
        }

        X509TrustManager trustManager = (X509TrustManager) trustManagers[0];

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, new TrustManager[] { trustManager }, null);
        socketFactory = sslContext.getSocketFactory();
    } catch (NoSuchAlgorithmException|KeyStoreException|KeyManagementException e) {
        Log.e(TAG, "Failed obtaining the SSL socket factory.");
        return;
    }
    String[] cipherSuites = socketFactory.getDefaultCipherSuites();
    ArrayList<String> allowedList = new ArrayList<>();
    for (String suite : cipherSuites) {
        if (!suite.contains("ECDH")) {
            allowedList.add(suite);
        }
    }
    ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
            .cipherSuites(allowedList.toArray(new String[0]))
            .supportsTlsExtensions(true)
            .build();
    specList.add(spec);
}
 
Example 35
Project: Okhttp-demo   File: HttpsUtils.java   View source code 5 votes vote down vote up
public static SSLSocketFactory initSSLSocketFactory() {
    SSLContext sslContext = null;
    try {
        sslContext = SSLContext.getInstance("SSL");
        X509TrustManager[] xTrustArray = new X509TrustManager[]
                {initTrustManager()};
        sslContext.init(null,
                xTrustArray, new SecureRandom());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return sslContext.getSocketFactory();
}
 
Example 36
Project: GitHub   File: CustomCipherSuites.java   View source code 5 votes vote down vote up
public CustomCipherSuites() throws GeneralSecurityException {
  // Configure cipher suites to demonstrate how to customize which cipher suites will be used for
  // an OkHttp request. In order to be selected a cipher suite must be included in both OkHttp's
  // connection spec and in the SSLSocket's enabled cipher suites array. Most applications should
  // not customize the cipher suites list.
  List<CipherSuite> customCipherSuites = Arrays.asList(
      CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
      CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
      CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
      CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384);
  final ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
      .cipherSuites(customCipherSuites.toArray(new CipherSuite[0]))
      .build();

  X509TrustManager trustManager = defaultTrustManager();
  SSLSocketFactory sslSocketFactory = defaultSslSocketFactory(trustManager);
  SSLSocketFactory customSslSocketFactory = new DelegatingSSLSocketFactory(sslSocketFactory) {
    @Override protected SSLSocket configureSocket(SSLSocket socket) throws IOException {
      socket.setEnabledCipherSuites(javaNames(spec.cipherSuites()));
      return socket;
    }
  };

  client = new OkHttpClient.Builder()
      .connectionSpecs(Collections.singletonList(spec))
      .sslSocketFactory(customSslSocketFactory, trustManager)
      .build();
}
 
Example 37
Project: incubator-servicecomb-java-chassis   File: TestSSLSocketFactoryExt.java   View source code 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  SSLSocketFactory factory = Mockito.mock(SSLSocketFactoryExt.class);
  String[] ciphers = {"test"};

  String[] protos = {"test"};
  instance = new SSLSocketFactoryExt(factory, ciphers, protos);
}
 
Example 38
Project: alfresco-greenmail   File: DummySSLSocketFactory.java   View source code 5 votes vote down vote up
public DummySSLSocketFactory() {
    try {
        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(null,
                new TrustManager[]{new DummyTrustManager()},
                null);
        factory = (SSLSocketFactory) sslcontext.getSocketFactory();
    } catch (Exception ex) {
        ex.printStackTrace();
        System.exit(-1);
    }
}
 
Example 39
Project: oryx2   File: SecureAPIConfigIT.java   View source code 5 votes vote down vote up
@Test
public void testHTTPS() throws Exception {
  Config config = buildHTTPSConfig();
  startServer(config);

  // Turn off actual checking of the dummy SSL cert
  SSLContext sslContext = SSLContext.getInstance("SSL");
  sslContext.init(null, new TrustManager[] { ACCEPT_ALL_TM }, null);
  SSLSocketFactory originalFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
  HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());

  try {
    String response = Resources.toString(
        new URL("https://localhost:" + getHTTPSPort() + "/helloWorld"),
        StandardCharsets.UTF_8);
    assertEquals("Hello, World", response);
  } finally {
    // Restore original SSL factory
    HttpsURLConnection.setDefaultSSLSocketFactory(originalFactory);
    Files.delete(Paths.get(config.getString("oryx.serving.api.keystore-file")));
  }
}
 
Example 40
Project: AutoNet   File: OkHttpUtil.java   View source code 5 votes vote down vote up
private static SSLSocketFactory createSSLSocketFactory() {
    SSLSocketFactory ssfFactory = null;

    try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, new TrustManager[]{new TrustAllCerts()}, new SecureRandom());

        ssfFactory = sc.getSocketFactory();
    } catch (Exception e) {
    }

    return ssfFactory;
}