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

项目:iotgateway    文件:CertPemClientCredentials.java   
private SSLSocketFactory getSocketFactory() {
  try {
    Security.addProvider(new BouncyCastleProvider());

    TrustManagerFactory trustManagerFactory = createAndInitTrustManagerFactory();
    KeyManagerFactory keyManagerFactory = createAndInitKeyManagerFactory();

    SSLContext context = SSLContext.getInstance(TLS_VERSION);
    context.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

    return context.getSocketFactory();
  } catch (Exception e) {
    log.error("[{}:{}:{}:{}] Creating TLS factory failed!", caCert, cert, privateKey, password, e);
    throw new RuntimeException("Creating TLS factory failed!", e);
  }
}
项目:push-network-proxies    文件:SSLHelper.java   
public static SSLContext newSSLContext(final KeyStore ks, final String password,
    final String ksAlgorithm) throws InvalidSSLConfig {
    try {
        // Get a KeyManager and initialize it
        final KeyManagerFactory kmf = KeyManagerFactory.getInstance(ksAlgorithm);
        kmf.init(ks, password.toCharArray());

        // Get a TrustManagerFactory with the DEFAULT KEYSTORE, so we have all the certificates in cacerts trusted
        final TrustManagerFactory tmf = TrustManagerFactory.getInstance(ksAlgorithm);
        tmf.init((KeyStore) null);

        // Get the SSLContext to help create SSLSocketFactory
        final SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
        return sslContext;
    } catch (final GeneralSecurityException e) {
        throw new InvalidSSLConfig(e);
    }
}
项目:reactive-playing    文件:RxGitterClient.java   
private void emmit(FlowableEmitter<Message> emitter, String roomId) throws Exception {
    SSLContext sslCtx = SSLContext.getDefault();
    SSLEngine sslEngine = sslCtx.createSSLEngine("stream.gitter.im", 443);
    sslEngine.setUseClientMode(true);

    HttpClient
            .newClient("stream.gitter.im", 443)
            .secure(sslEngine)
            .createGet("/v1/rooms/" + roomId + "/chatMessages")
            .addHeader("Authorization", "Bearer 3cd4820adf59b6a7116f99d92f68a1b786895ce7")
            .flatMap(HttpClientResponse::getContent)
            .filter(bb -> bb.capacity() > 2)
            .map(MessageEncoder::mapToMessage)
            .doOnNext(m -> System.out.println("Log Emit: " + m))
            .subscribe(emitter::onNext, emitter::onError, emitter::onComplete);
}
项目:message-broker    文件:SslHandlerFactory.java   
public SslHandlerFactory(AmqpServerConfiguration configuration) throws KeyStoreException, IOException,
        CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException, KeyManagementException {
    KeyStore keyStore = getKeyStore(configuration.getSsl().getKeyStore().getType(),
                                    configuration.getSsl().getKeyStore().getLocation(),
                                    configuration.getSsl().getKeyStore().getPassword());
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(configuration.getSsl()
                                                                                     .getKeyStore()
                                                                                     .getCertType());
    keyManagerFactory.init(keyStore, configuration.getSsl().getKeyStore().getPassword().toCharArray());

    KeyStore trustStore = getKeyStore(configuration.getSsl().getTrustStore().getType(),
                                      configuration.getSsl().getTrustStore().getLocation(),
                                      configuration.getSsl().getTrustStore().getPassword());
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(configuration.getSsl()
                                                                           .getTrustStore()
                                                                           .getCertType());
    trustManagerFactory.init(trustStore);

    sslContext = SSLContext.getInstance(configuration.getSsl().getProtocol());
    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
}
项目:websocket-poc    文件:App.java   
@Bean
public RestTemplate restTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {

    SSLContext sslContext = SSLContexts.custom()
            .loadTrustMaterial(null, new TrustSelfSignedStrategy())
            .build();

    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
    CloseableHttpClient httpClient = HttpClients.custom()
            .setSSLSocketFactory(sslConnectionSocketFactory)
            .build();

    HttpComponentsClientHttpRequestFactory requestFactory =
            new HttpComponentsClientHttpRequestFactory();

    requestFactory.setHttpClient(httpClient);

    return new RestTemplate(requestFactory);
}
项目:ejabberd-api    文件:EjabberdApi.java   
private HttpURLConnection prepareConnection(Request request) throws IOException, RequestFailedException {
    final URL url = new URL(endpoint, MethodNameConverter.convert(request));
    final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    if (this.ignoreSllExceptions && connection instanceof HttpsURLConnection) {
        HttpsURLConnection sslConnection = (HttpsURLConnection) connection;
        try {
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, new TrustManager[]{new TrustEverythingManager()}, new SecureRandom());
            sslConnection.setHostnameVerifier(new DisabledHostnameVerifier());
            sslConnection.setSSLSocketFactory(sslContext.getSocketFactory());
        } catch (Exception e) {
            throw new RequestFailedException(e);
        }
    }
    connection.setRequestMethod("POST");
    if (this.username != null && this.password != null) {
        String authorization = Base64.getEncoder().encodeToString((username + ":" + password).getBytes(StandardCharsets.UTF_8));
        connection.addRequestProperty("Authorization", "Basic " + authorization);
    }
    return connection;
}
项目:habpanelviewer    文件:ConnectionUtil.java   
public static synchronized HttpURLConnection createUrlConnection(final String urlStr) throws IOException, GeneralSecurityException {
    final URL url = new URL(urlStr);
    SSLContext sslCtx = createSslContext();
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    if (urlConnection instanceof HttpsURLConnection) {
        ((HttpsURLConnection) urlConnection).setSSLSocketFactory(sslCtx.getSocketFactory());

        HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return hostname.equalsIgnoreCase(url.getHost());
            }
        };
        ((HttpsURLConnection) urlConnection).setHostnameVerifier(hostnameVerifier);
    }
    urlConnection.setConnectTimeout(200);

    return urlConnection;
}
项目:spring-cloud-dashboard    文件:HttpClientUtils.java   
/**
 * Will create a certificate-ignoring {@link SSLContext}. Please use with utmost caution as it undermines security,
 * but may be useful in certain testing or development scenarios.
 *
 * @return The SSLContext
 */
public static SSLContext buildCertificateIgnoringSslContext() {
    try {
        return SSLContexts
            .custom()
            .loadTrustMaterial(new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                    return true;
                }
            })
            .build();
    }
    catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
        throw new IllegalStateException("Unexpected exception while building the certificate-ignoring SSLContext.", e);
    }
}
项目:drift    文件:ApacheThriftMethodInvoker.java   
public ApacheThriftMethodInvoker(
        ListeningExecutorService executorService,
        ListeningScheduledExecutorService delayService,
        TTransportFactory transportFactory,
        TProtocolFactory protocolFactory,
        Duration connectTimeout,
        Duration requestTimeout,
        Optional<HostAndPort> socksProxy,
        Optional<SSLContext> sslContext)
{
    this.executorService = requireNonNull(executorService, "executorService is null");
    this.delayService = requireNonNull(delayService, "delayService is null");
    this.transportFactory = requireNonNull(transportFactory, "transportFactory is null");
    this.protocolFactory = requireNonNull(protocolFactory, "protocolFactory is null");
    this.connectTimeoutMillis = Ints.saturatedCast(requireNonNull(connectTimeout, "connectTimeout is null").toMillis());
    this.requestTimeoutMillis = Ints.saturatedCast(requireNonNull(requestTimeout, "requestTimeout is null").toMillis());
    this.socksProxy = requireNonNull(socksProxy, "socksProxy is null");
    this.sslContext = requireNonNull(sslContext, "sslContext is null");
}
项目:spring-credhub    文件:ClientHttpRequestFactoryFactory.java   
static ClientHttpRequestFactory usingOkHttp3(ClientOptions options)
        throws IOException, GeneralSecurityException {

    SSLSocketFactory socketFactory = SSLContext.getDefault().getSocketFactory();
    X509TrustManager trustManager = getTrustManager();

    Builder builder = new Builder().sslSocketFactory(socketFactory, trustManager);

    if (options.getConnectionTimeout() != null) {
        builder.connectTimeout(options.getConnectionTimeout(), TimeUnit.MILLISECONDS);
    }
    if (options.getReadTimeout() != null) {
        builder.readTimeout(options.getReadTimeout(), TimeUnit.MILLISECONDS);
    }

    return new OkHttp3ClientHttpRequestFactory(builder.build());
}
项目:GitHub    文件:URLConnectionTest.java   
@Test public void httpsWithCustomTrustManager() throws Exception {
  RecordingHostnameVerifier hostnameVerifier = new RecordingHostnameVerifier();
  RecordingTrustManager trustManager = new RecordingTrustManager(sslClient.trustManager);
  SSLContext sslContext = SSLContext.getInstance("TLS");
  sslContext.init(null, new TrustManager[] { trustManager }, null);

  urlFactory.setClient(urlFactory.client().newBuilder()
      .hostnameVerifier(hostnameVerifier)
      .sslSocketFactory(sslContext.getSocketFactory(), trustManager)
      .build());
  server.useHttps(sslClient.socketFactory, false);
  server.enqueue(new MockResponse().setBody("ABC"));
  server.enqueue(new MockResponse().setBody("DEF"));
  server.enqueue(new MockResponse().setBody("GHI"));

  URL url = server.url("/").url();
  assertContent("ABC", urlFactory.open(url));
  assertContent("DEF", urlFactory.open(url));
  assertContent("GHI", urlFactory.open(url));

  assertEquals(Arrays.asList("verify " + server.getHostName()), hostnameVerifier.calls);
  assertEquals(Arrays.asList("checkServerTrusted [CN=" + server.getHostName() + " 1]"),
      trustManager.calls);
}
项目:light-session-4j    文件:TestHttpClient.java   
public void setSSLContext(final SSLContext sslContext) {
    SchemeRegistry registry = getConnectionManager().getSchemeRegistry();
    registry.unregister("https");
    registry.register(new Scheme("https", 443, new SSLSocketFactory(sslContext)));

    /*
    if (DefaultServer.getHostAddress(DefaultServer.DEFAULT).equals("localhost")) {
        registry.register(new Scheme("https", 443, new SSLSocketFactory(sslContext)));
        registry.register(new Scheme("https", DefaultServer.getHostSSLPort("default"), new SSLSocketFactory(sslContext)));
    } else {
        registry.register(new Scheme("https", 443, new SSLSocketFactory(sslContext, NO_OP_VERIFIER)));
        registry.register(new Scheme("https", DefaultServer.getHostSSLPort("default"), new SSLSocketFactory(sslContext, NO_OP_VERIFIER)));
    }
    */

}
项目:MinimalFTP    文件:ConnectionHandler.java   
private void auth(String mechanism) throws IOException {
    mechanism = mechanism.toUpperCase();

    if(mechanism.equals("TLS") || mechanism.equals("TLS-C") ||
        mechanism.equals("SSL") || mechanism.equals("TLS-P")) {
        // No need to distinguish between TLS and SSL, as the protocol self-negotiate its level

        SSLContext ssl = con.getServer().getSSLContext();

        if(ssl == null) {
            con.sendResponse(431, "TLS/SSL is not available");
        } else if(con.isSSLEnabled()) {
            con.sendResponse(503, "TLS/SSL is already enabled");
        } else {
            con.sendResponse(234, "Enabling TLS/SSL...");
            con.enableSSL(ssl);
        }

    } else {
        con.sendResponse(502, "Unsupported mechanism");
    }
}
项目:qonduit    文件:WebSocketClient.java   
public WebSocketClient(SSLContext ssl, String hostname, int httpsPort, int wssPort, boolean doLogin,
        String username, String password, boolean hostVerificationEnabled, int bufferSize) {
    this.ssl = ssl;
    this.hostname = hostname;
    this.httpsPort = httpsPort;
    this.wssPort = wssPort;
    this.doLogin = doLogin;
    this.username = username;
    this.password = password;
    this.hostVerificationEnabled = hostVerificationEnabled;
    this.bufferSize = bufferSize;

    Preconditions.checkNotNull(hostname, "%s must be supplied", "host name");
    Preconditions.checkNotNull(httpsPort, "%s must be supplied", "HTTPS port");
    Preconditions.checkNotNull(wssPort, "%s must be supplied", "WSS port");

    if (doLogin
            && ((StringUtils.isEmpty(username) && !StringUtils.isEmpty(password) || (!StringUtils.isEmpty(username) && StringUtils
                    .isEmpty(password))))) {
        throw new IllegalArgumentException("Both username and password must be empty or non-empty");
    }

}
项目:athena    文件:Controller.java   
private void initSsl() throws Exception {

        TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        KeyStore ts = KeyStore.getInstance("JKS");
        ts.load(new FileInputStream(tsLocation), tsPwd);
        tmFactory.init(ts);

        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(new FileInputStream(ksLocation), ksPwd);
        kmf.init(ks, ksPwd);

        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(kmf.getKeyManagers(), tmFactory.getTrustManagers(), null);


    }
项目:lazycat    文件:JSSESocketFactory.java   
@Override
public String[] getEnableableProtocols(SSLContext context) {
    String[] requestedProtocols = endpoint.getSslEnabledProtocolsArray();
    if ((requestedProtocols == null) || (requestedProtocols.length == 0)) {
        return defaultServerProtocols;
    }

    List<String> protocols = new ArrayList<String>(Arrays.asList(requestedProtocols));
    protocols.retainAll(Arrays.asList(context.getSupportedSSLParameters().getProtocols()));

    if (protocols.isEmpty()) {
        log.warn(sm.getString("jsse.requested_protocols_not_supported", Arrays.asList(requestedProtocols)));
    }
    if (log.isDebugEnabled()) {
        log.debug(sm.getString("jsse.enableable_protocols", protocols));
        if (protocols.size() != requestedProtocols.length) {
            List<String> skipped = new ArrayList<String>(Arrays.asList(requestedProtocols));
            skipped.removeAll(protocols);
            log.debug(sm.getString("jsse.unsupported_protocols", skipped));
        }
    }
    return protocols.toArray(new String[protocols.size()]);
}
项目:java-pilosa    文件:ClientOptionsTest.java   
@Test
public void testCreate() throws KeyManagementException, NoSuchAlgorithmException {
    SSLContext sslContext = new SSLContextBuilder().build();
    ClientOptions options = ClientOptions.builder()
            .setConnectionPoolSizePerRoute(2)
            .setConnectionPoolTotalSize(50)
            .setConnectTimeout(100)
            .setSocketTimeout(1000)
            .setRetryCount(5)
            .setSslContext(sslContext)
            .build();
    assertEquals(2, options.getConnectionPoolSizePerRoute());
    assertEquals(50, options.getConnectionPoolTotalSize());
    assertEquals(100, options.getConnectTimeout());
    assertEquals(1000, options.getSocketTimeout());
    assertEquals(5, options.getRetryCount());
    assertEquals(sslContext, options.getSslContext());
}
项目:FirefoxData-android    文件:BaseResource.java   
private static ClientConnectionManager enableTLSConnectionManager() throws KeyManagementException, NoSuchAlgorithmException  {
  SSLContext sslContext = SSLContext.getInstance("TLS");
  sslContext.init(null, null, new SecureRandom());

  Logger.debug(LOG_TAG, "Using protocols and cipher suites for Android API " + android.os.Build.VERSION.SDK_INT);
  SSLSocketFactory sf = new SSLSocketFactory(sslContext, GlobalConstants.DEFAULT_PROTOCOLS, GlobalConstants.DEFAULT_CIPHER_SUITES, null);
  SchemeRegistry schemeRegistry = new SchemeRegistry();
  schemeRegistry.register(new Scheme("https", 443, sf));
  schemeRegistry.register(new Scheme("http", 80, new PlainSocketFactory()));
  ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(schemeRegistry);

  cm.setMaxTotal(MAX_TOTAL_CONNECTIONS);
  cm.setDefaultMaxPerRoute(MAX_CONNECTIONS_PER_ROUTE);
  connManager = cm;
  return cm;
}
项目:jdk8u-jdk    文件:JSSEServer.java   
JSSEServer(CipherTestUtils cipherTest, int serverPort,
        String protocol, String cipherSuite) throws Exception {
    super(cipherTest);
    this.serverPort = serverPort;
    SSLContext serverContext = SSLContext.getInstance("TLS");
    serverContext.init(new KeyManager[]{cipherTest.getServerKeyManager()},
            new TrustManager[]{cipherTest.getServerTrustManager()},
            CipherTestUtils.secureRandom);
    SSLServerSocketFactory factory =
            (SSLServerSocketFactory)serverContext.getServerSocketFactory();
    serverSocket =
            (SSLServerSocket) factory.createServerSocket(serverPort);
    serverSocket.setEnabledProtocols(protocol.split(","));
    serverSocket.setEnabledCipherSuites(cipherSuite.split(","));

    CipherTestUtils.printInfo(serverSocket);
}
项目:dremio-oss    文件:Backup.java   
public static BackupStats createBackup(DACConfig dacConfig, String userName, String password, KeyStore trustStore, URI uri) throws IOException {
  final JacksonJaxbJsonProvider provider = new JacksonJaxbJsonProvider();
  provider.setMapper(JSONUtil.prettyMapper());
  ClientBuilder clientBuilder = ClientBuilder.newBuilder()
      .register(provider)
      .register(MultiPartFeature.class);

  if (trustStore != null) {
    clientBuilder.trustStore(trustStore);
  } else {
    SSLContext sslContext = SSLHelper.newAllTrustingSSLContext("SSL");
    HostnameVerifier verifier = SSLHelper.newAllValidHostnameVerifier();
    clientBuilder.hostnameVerifier(verifier);
    clientBuilder.sslContext(sslContext);
  }

  final Client client = clientBuilder.build();
  WebTarget target = client.target(format("%s://%s:%d",
      dacConfig.webSSLEnabled ? "https" : "http", dacConfig.masterNode, dacConfig.getHttpPort())).path("apiv2");

  final UserLogin userLogin = new UserLogin(userName, password);
  final UserLoginSession userLoginSession = readEntity(UserLoginSession.class, target.path("/login").request(JSON).buildPost(Entity.json(userLogin)));


  return readEntity(BackupStats.class, target.path("/backup").request(JSON).header(HttpHeader.AUTHORIZATION.toString(),
    TokenUtils.AUTH_HEADER_PREFIX + userLoginSession.getToken()).buildPost(Entity.json(uri.toString())));
}
项目:elasticsearch_my    文件:AzureDiscoveryClusterFormationTests.java   
private static SSLContext getSSLContext() throws Exception {
    char[] passphrase = "keypass".toCharArray();
    KeyStore ks = KeyStore.getInstance("JKS");
    try (InputStream stream = AzureDiscoveryClusterFormationTests.class.getResourceAsStream("/test-node.jks")) {
        assertNotNull("can't find keystore file", stream);
        ks.load(stream, passphrase);
    }
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
    kmf.init(ks, passphrase);
    TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
    tmf.init(ks);
    SSLContext ssl = SSLContext.getInstance("TLS");
    ssl.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    return ssl;
}
项目:iotplatform    文件:MqttSslHandlerProvider.java   
public SslHandler getSslHandler() {
    try {
        URL ksUrl = Resources.getResource(keyStoreFile);
        File ksFile = new File(ksUrl.toURI());
        URL tsUrl = Resources.getResource(keyStoreFile);
        File tsFile = new File(tsUrl.toURI());

        TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        KeyStore trustStore = KeyStore.getInstance(keyStoreType);
        trustStore.load(new FileInputStream(tsFile), keyStorePassword.toCharArray());
        tmFactory.init(trustStore);

        KeyStore ks = KeyStore.getInstance(keyStoreType);

        ks.load(new FileInputStream(ksFile), keyStorePassword.toCharArray());
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(ks, keyPassword.toCharArray());

        KeyManager[] km = kmf.getKeyManagers();
        TrustManager x509wrapped = getX509TrustManager(tmFactory);
        TrustManager[] tm = {x509wrapped};
        SSLContext sslContext = SSLContext.getInstance(TLS);
        sslContext.init(km, tm, null);
        SSLEngine sslEngine = sslContext.createSSLEngine();
        sslEngine.setUseClientMode(false);
        sslEngine.setNeedClientAuth(false);
        sslEngine.setWantClientAuth(true);
        sslEngine.setEnabledProtocols(sslEngine.getSupportedProtocols());
        sslEngine.setEnabledCipherSuites(sslEngine.getSupportedCipherSuites());
        sslEngine.setEnableSessionCreation(true);
        return new SslHandler(sslEngine);
    } catch (Exception e) {
        log.error("Unable to set up SSL context. Reason: " + e.getMessage(), e);
        throw new RuntimeException("Failed to get SSL handler", e);
    }
}
项目:mDL-ILP    文件:NetUtils.java   
public static void setUpSSL(Context context) {
        // set up keystore
        try (InputStream clientInput = context.getResources().openRawResource(R.raw.rdw_poc_mdl_client_ca);
             //InputStream serverInput = context.getResources().openRawResource(R.raw.rdw_poc_ca)) {
             InputStream serverInput = context.getResources().openRawResource(R.raw.rdw_poc_ssl)) {
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            //java.security.cert.Certificate clientCA = cf.generateCertificate(clientInput);

            // This part sends my cert to server
//            KeyStore clientStore = KeyStore.getInstance("PKCS12");
//            clientStore.load(clientInput, "password".toCharArray());
            //clientStore.setCertificateEntry("", clientCA);

//            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
//            keyManagerFactory.init(clientStore, null);

            // this part trusts a remote certificate
            java.security.cert.Certificate serverCA = cf.generateCertificate(serverInput);
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            KeyStore serverStore = KeyStore.getInstance("PKCS12");
            serverStore.load(null, null);
            serverStore.setCertificateEntry("", serverCA);
            tmf.init(serverStore);

            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, tmf.getTrustManagers(), null);

            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        } catch (Exception e) {
            Log.e("TLS", "Something went wrong", e);
        }
    }
项目:lams    文件:TLSProtocolSocketFactory.java   
/**
 * Do initialization that is common across constructors.
 * 
 * @throws IllegalArgumentException thrown if the given key or trust manager can not be used to create the
 *             {@link SSLContext} used to create new sockets
 */
protected void init() throws IllegalArgumentException {
    try {
        sslContext = SSLContext.getInstance("SSL");
        sslContext.init(keyManagers, trustManagers, secureRandom);
    } catch (GeneralSecurityException e) {
        throw new IllegalArgumentException("Error create SSL context", e);
    }
}
项目:lams    文件:Undertow.java   
private ListenerConfig(final ListenerType type, final int port, final String host, SSLContext sslContext) {
    this.type = type;
    this.port = port;
    this.host = host;
    this.keyManagers = null;
    this.trustManagers = null;
    this.sslContext = sslContext;
}
项目:openjdk-jdk10    文件:HttpsCreateSockTest.java   
/**
 * Https Server
 */
public void startHttpsServer() throws IOException, NoSuchAlgorithmException  {
    httpsServer = com.sun.net.httpserver.HttpsServer.create(new InetSocketAddress(0), 0);
    httpsServer.createContext("/", new MyHandler());
    httpsServer.setHttpsConfigurator(new HttpsConfigurator(SSLContext.getDefault()));
    httpsServer.start();
}
项目:LearningSummary    文件:SSLClient.java   
public void init() throws Exception {
    //这个类是原生包中的SSL连接的上下文类
    SSLContext context = SSLContext.getInstance("SSL");

    //客户端证书库
    KeyStore clientKeystore = KeyStore.getInstance("PKCS12");
    FileInputStream keystoreFis = new FileInputStream(keystorePath);
    clientKeystore.load(keystoreFis, keystorePassword.toCharArray());
    //信任证书库
    KeyStore trustKeystore = KeyStore.getInstance("jks");
    FileInputStream trustKeystoreFis = new FileInputStream(trustKeystorePath);
    trustKeystore.load(trustKeystoreFis, keystoreTrustPassword.toCharArray());

    //密钥库
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("sunx509");
    kmf.init(clientKeystore, keystorePassword.toCharArray());

    //信任库
    TrustManagerFactory tmf = TrustManagerFactory.getInstance("sunx509");
    tmf.init(trustKeystore);

    //初始化SSL上下文
    context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

    //原生包SSLSocket方式
    sslSocket = (SSLSocket)context.getSocketFactory().createSocket(host, port);

    trustKeystoreFis.close();
    keystoreFis.close();

    System.out.println("SSLClient initialized.");

}
项目:GitHub    文件:ConnectionProcessor.java   
ConnectionProcessor(final String serverURL, final CountlyStore store, final DeviceId deviceId, final SSLContext sslContext) {
    serverURL_ = serverURL;
    store_ = store;
    deviceId_ = deviceId;
    sslContext_ = sslContext;

    // HTTP connection reuse which was buggy pre-froyo
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) {
        System.setProperty("http.keepAlive", "false");
    }
}
项目:pay    文件:HttpsRequest.java   
private void init() throws IOException, KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException {

        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        FileInputStream instream = new FileInputStream(new File(config.getCertLocalPath()));//加载本地的证书进行https加密传输
        try {
            keyStore.load(instream,config.getCertPassword().toCharArray());//设置证书密码
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            instream.close();
        }

        // Trust own CA and all self-signed certs
        SSLContext sslcontext = SSLContexts.custom()
                .loadKeyMaterial(keyStore, config.getCertPassword().toCharArray())
                .build();
        // Allow TLSv1 protocol only
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslcontext,
                new String[]{"TLSv1"},
                null,
                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);

        httpClient = HttpClients.custom()
                .setSSLSocketFactory(sslsf)
                .build();

        //根据默认超时限制初始化requestConfig
        requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).build();

        hasInit = true;
    }
项目:lams    文件:SSLSocketFactory.java   
private static SSLContext createSSLContext(
        String algorithm,
        final KeyStore keystore,
        final String keystorePassword,
        final KeyStore truststore,
        final SecureRandom random,
        final TrustStrategy trustStrategy)
            throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, KeyManagementException {
    if (algorithm == null) {
        algorithm = TLS;
    }
    KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(
            KeyManagerFactory.getDefaultAlgorithm());
    kmfactory.init(keystore, keystorePassword != null ? keystorePassword.toCharArray(): null);
    KeyManager[] keymanagers =  kmfactory.getKeyManagers();
    TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(
            TrustManagerFactory.getDefaultAlgorithm());
    tmfactory.init(truststore);
    TrustManager[] trustmanagers = tmfactory.getTrustManagers();
    if (trustmanagers != null && trustStrategy != null) {
        for (int i = 0; i < trustmanagers.length; i++) {
            TrustManager tm = trustmanagers[i];
            if (tm instanceof X509TrustManager) {
                trustmanagers[i] = new TrustManagerDecorator(
                        (X509TrustManager) tm, trustStrategy);
            }
        }
    }

    SSLContext sslcontext = SSLContext.getInstance(algorithm);
    sslcontext.init(keymanagers, trustmanagers, random);
    return sslcontext;
}
项目:opentest    文件:HttpRequest.java   
private CloseableHttpClient createHttpClient(boolean ignoreCert) {
    try {
        RequestConfig requestConfig = RequestConfig.custom()
                .setCookieSpec(CookieSpecs.STANDARD)
                .build();

        CloseableHttpClient client;

        if (ignoreCert) {
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(new KeyManager[0], new TrustManager[]{new NoopTrustManager()}, new SecureRandom());
            SSLContext.setDefault(sslContext);

            SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(
                    sslContext, NoopHostnameVerifier.INSTANCE);
            client = HttpClients.custom()
                    .disableRedirectHandling()
                    .setDefaultRequestConfig(requestConfig)
                    .setSSLSocketFactory(sslSocketFactory)
                    .build();
        } else {
            client = HttpClientBuilder.create()
                    .disableRedirectHandling()
                    .setDefaultRequestConfig(requestConfig)
                    .build();
        }

        return client;
    } catch (Throwable ex) {
        throw new RuntimeException(String.format(
                "Failed to create http client (ignoreCert = %s)",
                ignoreCert), ex);
    }
}
项目:tomcat7    文件:JSSESocketFactory.java   
@Override
public String[] getEnableableProtocols(SSLContext context) {
    String[] requestedProtocols = endpoint.getSslEnabledProtocolsArray();
    if ((requestedProtocols == null) || (requestedProtocols.length == 0)) {
        return defaultServerProtocols;
    }

    List<String> protocols = new ArrayList<String>(
            Arrays.asList(requestedProtocols));
    protocols.retainAll(Arrays.asList(context.getSupportedSSLParameters()
            .getProtocols()));

    if (protocols.isEmpty()) {
        log.warn(sm.getString("jsse.requested_protocols_not_supported",
                Arrays.asList(requestedProtocols)));
    }
    if (log.isDebugEnabled()) {
        log.debug(sm.getString("jsse.enableable_protocols", protocols));
        if (protocols.size() != requestedProtocols.length) {
            List<String> skipped = new ArrayList<String>(
                    Arrays.asList(requestedProtocols));
            skipped.removeAll(protocols);
            log.debug(sm.getString("jsse.unsupported_protocols", skipped));
        }
    }
    return protocols.toArray(new String[protocols.size()]);
}
项目:GitHub    文件:OkHttpClient.java   
private SSLSocketFactory systemDefaultSslSocketFactory(X509TrustManager trustManager) {
  try {
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, new TrustManager[] { trustManager }, null);
    return sslContext.getSocketFactory();
  } catch (GeneralSecurityException e) {
    throw assertionError("No System TLS", e); // The system has no TLS. Just give up.
  }
}
项目:WLT3Serial    文件:CustomSSLSocketFactory.java   
public CustomSSLSocketFactory() throws Exception {
    super();
    String prot = System.getProperty("jdk.tls.client.protocols");
    if(prot.contains("SSL")) {
        prot = "SSL";
    }

    //disable all SSL/TLS certificate validation, and get reference to current system-wide SSLSocketFactory
    SSLContext context = SSLContext.getInstance(prot);
    TrustManager[] trustAll = new TrustManager[] {new TrustAllCertsManager()};
    context.init(null,trustAll,null);
    defaultSSLSocketFactory = context.getSocketFactory();
}
项目:onedatashare    文件:HTTPInitializer.java   
private SSLEngine getSsl(String proto) throws NoSuchAlgorithmException {
  String protocol = (proto == null) ? "TLS" : proto;
  SSLContext context = SSLContext.getInstance(protocol);
  try {
    context.init(null, null, null);
  } catch (KeyManagementException e) {
    System.err.println(e.getMessage());
  }

  return context.createSSLEngine();
}
项目:GitHub    文件:CustomTrust.java   
public CustomTrust() {
  X509TrustManager trustManager;
  SSLSocketFactory sslSocketFactory;
  try {
    trustManager = trustManagerForCertificates(trustedCertificatesInputStream());
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, new TrustManager[] { trustManager }, null);
    sslSocketFactory = sslContext.getSocketFactory();
  } catch (GeneralSecurityException e) {
    throw new RuntimeException(e);
  }

  client = new OkHttpClient.Builder()
      .sslSocketFactory(sslSocketFactory, trustManager)
      .build();
}
项目:BTNotifierAndroid    文件:SslNetworkConnectionProvider.java   
@Override
public ServerSocket getServerSocket() throws Exception {
    SSLContext sslContext = SslUtils.getSSLContext(trustStore);
    SSLServerSocketFactory serverSocketFactory = sslContext.getServerSocketFactory();
    SSLServerSocket serverSocket = (SSLServerSocket) serverSocketFactory.createServerSocket(port);
    serverSocket.setNeedClientAuth(true);
    return serverSocket;
}
项目:GitHub    文件:SampleServer.java   
public static void main(String[] args) throws Exception {
  if (args.length != 4) {
    System.out.println("Usage: SampleServer <keystore> <password> <root file> <port>");
    return;
  }

  String keystoreFile = args[0];
  String password = args[1];
  String root = args[2];
  int port = Integer.parseInt(args[3]);

  SSLContext sslContext = sslContext(keystoreFile, password);
  SampleServer server = new SampleServer(sslContext, root, port);
  server.run();
}
项目:GitHub    文件:MockWebServer.java   
private void processHandshakeFailure(Socket raw) throws Exception {
  SSLContext context = SSLContext.getInstance("TLS");
  context.init(null, new TrustManager[] {UNTRUSTED_TRUST_MANAGER}, new SecureRandom());
  SSLSocketFactory sslSocketFactory = context.getSocketFactory();
  SSLSocket socket = (SSLSocket) sslSocketFactory.createSocket(
      raw, raw.getInetAddress().getHostAddress(), raw.getPort(), true);
  try {
    socket.startHandshake(); // we're testing a handshake failure
    throw new AssertionError();
  } catch (IOException expected) {
  }
  socket.close();
}
项目:ScriptSpider    文件:HttpUtils.java   
/**
 * 创建httpclient连接池,并初始化httpclient
 */
public void init() {
    try {
        SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null,
                new TrustSelfSignedStrategy())
                .build();
        HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.getDefaultHostnameVerifier();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslcontext, hostnameVerifier);
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", sslsf)
                .build();
        httpClientConnectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        // Increase max total connection to 200
        httpClientConnectionManager.setMaxTotal(maxTotalPool);
        // Increase default max connection per route to 20
        httpClientConnectionManager.setDefaultMaxPerRoute(maxConPerRoute);
        SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(socketTimeout).build();
        httpClientConnectionManager.setDefaultSocketConfig(socketConfig);
    } catch (Exception e) {

    }
}