Java Code Examples for javax.net.ssl.SSLContext

The following are top voted examples for showing how to use javax.net.ssl.SSLContext. 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: iotgateway   File: CertPemClientCredentials.java   View source code 10 votes vote down vote up
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);
  }
}
 
Example 2
Project: push-network-proxies   File: SSLHelper.java   View source code 9 votes vote down vote up
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);
    }
}
 
Example 3
Project: websocket-poc   File: App.java   View source code 8 votes vote down vote up
@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);
}
 
Example 4
Project: reactive-playing   File: RxGitterClient.java   View source code 8 votes vote down vote up
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);
}
 
Example 5
Project: message-broker   File: SslHandlerFactory.java   View source code 7 votes vote down vote up
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);
}
 
Example 6
Project: spring-cloud-dashboard   File: HttpClientUtils.java   View source code 7 votes vote down vote up
/**
 * 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);
	}
}
 
Example 7
Project: ejabberd-api   File: EjabberdApi.java   View source code 7 votes vote down vote up
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;
}
 
Example 8
Project: habpanelviewer   File: ConnectionUtil.java   View source code 6 votes vote down vote up
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;
}
 
Example 9
Project: drift   File: ApacheThriftMethodInvoker.java   View source code 6 votes vote down vote up
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");
}
 
Example 10
Project: spring-credhub   File: ClientHttpRequestFactoryFactory.java   View source code 6 votes vote down vote up
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());
}
 
Example 11
Project: GitHub   File: URLConnectionTest.java   View source code 6 votes vote down vote up
@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);
}
 
Example 12
Project: light-session-4j   File: TestHttpClient.java   View source code 6 votes vote down vote up
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)));
    }
    */

}
 
Example 13
Project: MinimalFTP   File: ConnectionHandler.java   View source code 6 votes vote down vote up
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");
    }
}
 
Example 14
Project: qonduit   File: WebSocketClient.java   View source code 6 votes vote down vote up
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");
    }

}
 
Example 15
Project: athena   File: Controller.java   View source code 6 votes vote down vote up
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);


    }
 
Example 16
Project: lazycat   File: JSSESocketFactory.java   View source code 6 votes vote down vote up
@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()]);
}
 
Example 17
Project: java-pilosa   File: ClientOptionsTest.java   View source code 6 votes vote down vote up
@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());
}
 
Example 18
Project: FirefoxData-android   File: BaseResource.java   View source code 6 votes vote down vote up
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;
}
 
Example 19
Project: jdk8u-jdk   File: JSSEServer.java   View source code 6 votes vote down vote up
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);
}
 
Example 20
Project: dremio-oss   File: Backup.java   View source code 5 votes vote down vote up
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())));
}
 
Example 21
Project: elasticsearch_my   File: AzureDiscoveryClusterFormationTests.java   View source code 5 votes vote down vote up
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;
}
 
Example 22
Project: iotplatform   File: MqttSslHandlerProvider.java   View source code 5 votes vote down vote up
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);
    }
}
 
Example 23
Project: mDL-ILP   File: NetUtils.java   View source code 5 votes vote down vote up
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);
        }
    }
 
Example 24
Project: lams   File: TLSProtocolSocketFactory.java   View source code 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 25
Project: lams   File: Undertow.java   View source code 5 votes vote down vote up
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;
}
 
Example 26
Project: openjdk-jdk10   File: HttpsCreateSockTest.java   View source code 5 votes vote down vote up
/**
 * 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();
}
 
Example 27
Project: LearningSummary   File: SSLClient.java   View source code 5 votes vote down vote up
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.");
	
}
 
Example 28
Project: GitHub   File: ConnectionProcessor.java   View source code 5 votes vote down vote up
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");
    }
}
 
Example 29
Project: pay   File: HttpsRequest.java   View source code 5 votes vote down vote up
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;
    }
 
Example 30
Project: lams   File: SSLSocketFactory.java   View source code 5 votes vote down vote up
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;
}
 
Example 31
Project: opentest   File: HttpRequest.java   View source code 5 votes vote down vote up
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);
    }
}
 
Example 32
Project: tomcat7   File: JSSESocketFactory.java   View source code 5 votes vote down vote up
@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()]);
}
 
Example 33
Project: GitHub   File: OkHttpClient.java   View source code 5 votes vote down vote up
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.
  }
}
 
Example 34
Project: WLT3Serial   File: CustomSSLSocketFactory.java   View source code 5 votes vote down vote up
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();
}
 
Example 35
Project: onedatashare   File: HTTPInitializer.java   View source code 5 votes vote down vote up
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();
}
 
Example 36
Project: GitHub   File: CustomTrust.java   View source code 5 votes vote down vote up
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();
}
 
Example 37
Project: BTNotifierAndroid   File: SslNetworkConnectionProvider.java   View source code 5 votes vote down vote up
@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;
}
 
Example 38
Project: GitHub   File: SampleServer.java   View source code 5 votes vote down vote up
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();
}
 
Example 39
Project: GitHub   File: MockWebServer.java   View source code 5 votes vote down vote up
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();
}
 
Example 40
Project: ScriptSpider   File: HttpUtils.java   View source code 5 votes vote down vote up
/**
 * 创建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) {

    }
}