Java 类javax.net.ssl.SSLSocketFactory 实例源码

项目:GitHub    文件:Address.java   
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;
}
项目:pcloud-networking-java    文件:RealConnection.java   
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();
        }
    }
}
项目:GitHub    文件:Address.java   
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;
}
项目:JCurl    文件:JCurl.java   
/**
 * 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;
}
项目:jdk8u-jdk    文件:ConnectorBootstrap.java   
@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;
}
项目:PeSanKita-lib    文件:WebSocketConnection.java   
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);
  }
}
项目:GitHub    文件:ConnectionSpecTest.java   
@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));
}
项目:JAVA-    文件:HTTPSCoder.java   
/**
 * 获得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();

}
项目:parabuild-ci    文件:HsqlSocketFactorySecure.java   
/**
 * 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;
}
项目:intellij-mattermost-plugin    文件:MattermostClient.java   
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();
}
项目:JRediClients    文件:JedisPool.java   
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());
    }
}
项目:iBase4J    文件:HTTPSPKCSCoder.java   
/**
 * 获得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();

}
项目:GitHub    文件:ConnectionSpecTest.java   
@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));
}
项目:JRediClients    文件:JedisClusterInfoCache.java   
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();
    }
}
项目:cornerstone    文件:SecurityUtil.java   
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;
    }
项目:lemon    文件:CdnUtils.java   
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());
}
项目:jdk8u-jdk    文件:HttpsURLConnection.java   
/**
 * 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;
}
项目:super-volley    文件:ClientSSLSocketFactory.java   
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;
}
项目:Tusky    文件:OkHttpUtils.java   
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;
}
项目:lighthouse    文件:DefaultHttpClientConnectionFactory.java   
@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);
}
项目:bubichain-sdk-java    文件:HttpKit.java   
/**
 *  鍙戦�丳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();
}
项目:openjdk-jdk10    文件:StartTlsResponseImpl.java   
private SSLSocketFactory getDefaultFactory() throws IOException {

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

        return (defaultFactory =
            (SSLSocketFactory) SSLSocketFactory.getDefault());
    }
项目:DNASDKJava    文件:RestHttp.java   
/**
 * 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();
}
项目:GitHub    文件:Platform.java   
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;
  }
}
项目:openjdk-jdk10    文件:UnboundSSLUtils.java   
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);
}
项目:qonduit    文件:TwoWaySSLFailureIT.java   
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();
}
项目:GitHub    文件:ConnectionSpecTest.java   
@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);
}
项目:BiglyBT    文件:SESecurityManagerImpl.java   
@Override
public SSLSocketFactory
installServerCertificate(
    URL     url )
{
    return( SESecurityManager.installServerCertificates( url ));
}
项目:android-util2    文件:HttpsHelper.java   
/**
     * 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;
    }
项目:GitHub    文件:ClientAuthTest.java   
@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());
}
项目:okwallet    文件:RequestWalletBalanceTask.java   
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);
    }
}
项目:GitHub    文件:SocketRecorder.java   
/** 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);
    }
  };
}
项目:GitHub    文件:URLConnectionTest.java   
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());
}
项目:Tusky    文件:OkHttpUtils.java   
/**
 * 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);
}
项目:Okhttp-demo    文件:HttpsUtils.java   
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();
}
项目:GitHub    文件:CustomCipherSuites.java   
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();
}
项目:incubator-servicecomb-java-chassis    文件:TestSSLSocketFactoryExt.java   
@Before
public void setUp() throws Exception {
  SSLSocketFactory factory = Mockito.mock(SSLSocketFactoryExt.class);
  String[] ciphers = {"test"};

  String[] protos = {"test"};
  instance = new SSLSocketFactoryExt(factory, ciphers, protos);
}
项目:alfresco-greenmail    文件:DummySSLSocketFactory.java   
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);
    }
}
项目:oryx2    文件:SecureAPIConfigIT.java   
@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")));
  }
}
项目:AutoNet    文件:OkHttpUtil.java   
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;
}