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   Source Code and License 11 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   Source Code and License 10 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   Source Code and License 9 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   Source Code and License 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: ejabberd-api   File: EjabberdApi.java   Source Code and License 8 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 6
Project: message-broker   File: SslHandlerFactory.java   Source Code and License 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 7
Project: spring-cloud-dashboard   File: HttpClientUtils.java   Source Code and License 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 8
Project: habpanelviewer   File: ConnectionUtil.java   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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: WLT3Serial   File: CustomSSLSocketFactory.java   Source Code and License 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 34
Project: onedatashare   File: HTTPInitializer.java   Source Code and License 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 35
Project: GitHub   File: CustomTrust.java   Source Code and License 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 36
Project: BTNotifierAndroid   File: SslNetworkConnectionProvider.java   Source Code and License 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 37
Project: GitHub   File: SampleServer.java   Source Code and License 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 38
Project: ScriptSpider   File: HttpUtils.java   Source Code and License 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) {

    }
}
 
Example 39
Project: push-network-proxies   File: SSLHelper.java   Source Code and License 5 votes vote down vote up
public static SSLContext newSSLContext(final InputStream cert, final String password,
    final String ksType, final String ksAlgorithm) throws InvalidSSLConfig {
    try {
        final KeyStore ks = KeyStore.getInstance(ksType);
        ks.load(cert, password.toCharArray());
        return newSSLContext(ks, password, ksAlgorithm);
    } catch (final Exception e) {
        throw new InvalidSSLConfig(e);
    }
}
 
Example 40
Project: LearningSummary   File: SSLServer.java   Source Code and License 5 votes vote down vote up
public void init() throws Exception {
	
	//这个类是原生包中的SSL连接的上下文类
	SSLContext context = SSLContext.getInstance("SSL");
	
	//服务器端证书库
	KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
	FileInputStream keystoreFis = new FileInputStream(keystorePath);
	keystore.load(keystoreFis, keystorePassword.toCharArray());
	//信任证书库
	KeyStore trustKeystore = KeyStore.getInstance("jks");
	FileInputStream trustKeystoreFis = new FileInputStream(trustKeystorePath);
	trustKeystore.load(trustKeystoreFis, truststorePassword.toCharArray());
	
	//密钥库
	KeyManagerFactory kmf = KeyManagerFactory.getInstance("sunx509");
	kmf.init(keystore, keystorePassword.toCharArray());

	//信任库
	TrustManagerFactory tmf = TrustManagerFactory.getInstance("sunx509");
	tmf.init(trustKeystore);
	
	//初始化SSL上下文
	context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
	//初始化SSLSocket
	sslServerSocket = (SSLServerSocket)context.getServerSocketFactory().createServerSocket(port);
	//设置这个SSLServerSocket需要授权的客户端访问
	sslServerSocket.setNeedClientAuth(true);
	
	keystoreFis.close();
	trustKeystoreFis.close();
	System.out.println("SSLServer initialized.");
}
 
Example 41
Project: incubator-servicecomb-java-chassis   File: SSLManager.java   Source Code and License 5 votes vote down vote up
public static SSLSocketFactory createSSLSocketFactory(SSLOption option, SSLCustom custom) {
  SSLContext context = createSSLContext(option, custom);
  SSLSocketFactory factory = context.getSocketFactory();
  String[] supported = factory.getSupportedCipherSuites();
  String[] eanbled = option.getCiphers().split(",");
  return new SSLSocketFactoryExt(factory, getEnabledCiphers(supported, eanbled),
      option.getProtocols().split(","));
}
 
Example 42
Project: lams   File: SSLSocketFactory.java   Source Code and License 5 votes vote down vote up
/**
 * @since 4.1
 */
public SSLSocketFactory(
        final SSLContext sslContext, final X509HostnameVerifier hostnameVerifier) {
    super();
    if (sslContext == null) {
        throw new IllegalArgumentException("SSL context may not be null");
    }
    this.socketfactory = sslContext.getSocketFactory();
    this.hostnameVerifier = hostnameVerifier;
    this.nameResolver = null;
}
 
Example 43
Project: NioSmtpClient   File: FakeTlsContext.java   Source Code and License 5 votes vote down vote up
public static SSLContext createContext() {
  try {
    JdkSslContext nettyContext = (JdkSslContext) SslContextBuilder
        .forServer(getKeyManagerFactory())
        .sslProvider(SslProvider.JDK)
        .trustManager(InsecureTrustManagerFactory.INSTANCE)
        .build();

    return nettyContext.context();
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
 
Example 44
Project: incubator-servicecomb-java-chassis   File: SSLManagerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testCreateSSLSocketIOException() {
  SSLOption option = SSLOption.build(DIR + "/server.ssl.properties");

  SSLCustom custom = new SSLCustom() {
    @Override
    public String getFullPath(String filename) {
      return DIR + "/ssl/" + filename;
    }

    @Override
    public char[] decode(char[] encrypted) {
      return encrypted;
    }
  };

  new MockUp<SSLContext>() {
    @Mock
    public final SSLContext getInstance(String type) throws IOException {
      throw new IOException();
    }
  };

  try {
    SSLSocket context = SSLManager.createSSLSocket(option, custom);
    Assert.assertNotNull(context);
  } catch (Exception e) {
    Assert.assertEquals("java.lang.IllegalArgumentException", e.getClass().getName());
  }
}
 
Example 45
Project: an2linuxclient   File: TlsHelper.java   Source Code and License 5 votes vote down vote up
public static SSLContext getNotificationTlsContext(Context c, Certificate serverCert){
    try {
        SSLContext tlsContext = SSLContext.getInstance(TLS_VERSIONS[0]);

        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, null);
        keyStore.setKeyEntry("key", RsaHelper.getPrivateKey(c), "".toCharArray(),
                new Certificate[]{TlsHelper.getCertificate(c)});
        keyStore.setCertificateEntry("serverCert", serverCert);

        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, "".toCharArray());

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(keyStore);

        tlsContext.init(keyManagerFactory.getKeyManagers(), tmf.getTrustManagers(), null);
        return tlsContext;
    } catch (Exception e){
        Log.e("TlsHelper", "getNotificationTlsContext");
        Log.e("StackTrace", Log.getStackTraceString(e));
        return null;
    }
}
 
Example 46
Project: xxpay-master   File: HttpClientUtil.java   Source Code and License 5 votes vote down vote up
/**
 * 获取SSLContext
 * @param trustPasswd
 * @param keyPasswd
 * @return
 * @throws NoSuchAlgorithmException 
 * @throws KeyStoreException 
 * @throws IOException 
 * @throws CertificateException 
 * @throws UnrecoverableKeyException 
 * @throws KeyManagementException 
 */
public static SSLContext getSSLContext(
		FileInputStream trustFileInputStream, String trustPasswd,
		FileInputStream keyFileInputStream, String keyPasswd)
		throws NoSuchAlgorithmException, KeyStoreException,
		CertificateException, IOException, UnrecoverableKeyException,
		KeyManagementException {

	// ca
	TrustManagerFactory tmf = TrustManagerFactory.getInstance(HttpClientUtil.SunX509);
	KeyStore trustKeyStore = KeyStore.getInstance(HttpClientUtil.JKS);
	trustKeyStore.load(trustFileInputStream, HttpClientUtil
			.str2CharArray(trustPasswd));
	tmf.init(trustKeyStore);

	final char[] kp = HttpClientUtil.str2CharArray(keyPasswd);
	KeyManagerFactory kmf = KeyManagerFactory.getInstance(HttpClientUtil.SunX509);
	KeyStore ks = KeyStore.getInstance(HttpClientUtil.PKCS12);
	ks.load(keyFileInputStream, kp);
	kmf.init(ks, kp);

	SecureRandom rand = new SecureRandom();
	SSLContext ctx = SSLContext.getInstance(HttpClientUtil.TLS);
	ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), rand);

	return ctx;
}
 
Example 47
Project: Wechat-Group   File: WxMpPayServiceImpl.java   Source Code and License 5 votes vote down vote up
private String executeWithKey(String url, String requestStr) throws WxErrorException {
  try {
    SSLContext sslContext = getConfig().getSslContext();
    if (null == sslContext) {
      throw new IllegalArgumentException("请先初始化配置类(即WxMpConfigStorage的实现类)中的SSLContext!");
    }

    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[]{"TLSv1"}, null,
      new DefaultHostnameVerifier());

    HttpPost httpPost = new HttpPost(url);
    if (this.wxMpService.getHttpProxy() != null) {
      httpPost.setConfig(RequestConfig.custom().setProxy(this.wxMpService.getHttpProxy()).build());
    }

    try (CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build()) {
      httpPost.setEntity(new StringEntity(new String(requestStr.getBytes("UTF-8"), "ISO-8859-1")));
      try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
        String result = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
        this.log.debug("\n[URL]:  {}\n[PARAMS]: {}\n[RESPONSE]: {}", url, requestStr, result);
        return result;
      }
    } finally {
      httpPost.releaseConnection();
    }
  } catch (Exception e) {
    this.log.error("\n[URL]:  {}\n[PARAMS]: {}\n[EXCEPTION]: {}", url, requestStr, e.getMessage());
    throw new WxErrorException(WxError.newBuilder().setErrorCode(-1).setErrorMsg(e.getMessage()).build(), e);
  }
}
 
Example 48
Project: openjdk-jdk10   File: ConnectorBootstrap.java   Source Code and License 5 votes vote down vote up
private HostAwareSslSocketFactory(SSLContext ctx,
                                  String[] enabledCipherSuites,
                                  String[] enabledProtocols,
                                  boolean sslNeedClientAuth,
                                  String bindAddress) throws IllegalArgumentException {
    this.context = ctx;
    this.bindAddress = bindAddress;
    this.enabledProtocols = enabledProtocols;
    this.enabledCipherSuites = enabledCipherSuites;
    this.needClientAuth = sslNeedClientAuth;
    checkValues(ctx, enabledCipherSuites, enabledProtocols);
}
 
Example 49
Project: nifi-jms-jndi   File: JMSConnectionFactoryProvider.java   Source Code and License 5 votes vote down vote up
/**
 * This operation follows standard bean convention by matching property name
 * to its corresponding 'setter' method. Once the method was located it is
 * invoked to set the corresponding property to a value provided by during
 * service configuration. For example, 'channel' property will correspond to
 * 'setChannel(..) method and 'queueManager' property will correspond to
 * setQueueManager(..) method with a single argument.
 *
 * There are also few adjustments to accommodate well known brokers. For
 * example ActiveMQ ConnectionFactory accepts address of the Message Broker
 * in a form of URL while IBMs in the form of host/port pair (more common).
 * So this method will use value retrieved from the 'BROKER_URI' static
 * property 'as is' if ConnectionFactory implementation is coming from
 * ActiveMQ and for all others (for now) the 'BROKER_URI' value will be
 * split on ':' and the resulting pair will be used to execute
 * setHostName(..) and setPort(..) methods on the provided
 * ConnectionFactory. This may need to be maintained and adjusted to
 * accommodate other implementation of ConnectionFactory, but only for
 * URL/Host/Port issue. All other properties are set as dynamic properties
 * where user essentially provides both property name and value, The bean
 * convention is also explained in user manual for this component with links
 * pointing to documentation of various ConnectionFactories.
 *
 * @see #setProperty(String, String) method
 */
private void setConnectionFactoryProperties(ConfigurationContext context) {
    for (final Entry<PropertyDescriptor, String> entry : context.getProperties().entrySet()) {
        PropertyDescriptor descriptor = entry.getKey();
        String propertyName = descriptor.getName();
        if (descriptor.isDynamic()) {
            this.setProperty(propertyName, entry.getValue());
        } else {
            if (propertyName.equals(BROKER)) {
                String impl = context.getProperty(CONNECTION_FACTORY_IMPL).evaluateAttributeExpressions().getValue();
                boolean isSolace  = "com.solacesystems.jms.SolConnectionFactoryImpl".equals(impl);
                if (impl.startsWith("org.apache.activemq")) {
                    this.setProperty("brokerURL", entry.getValue());
                } else {
                    String val = entry.getValue();
                    if(val != null) {
                        String[] hostPort = val.split(":");
                        if (hostPort.length == 2) {
                            this.setProperty(isSolace? "Host" :"hostName", hostPort[0]);
                            this.setProperty("port", hostPort[1]);
                        } else if (hostPort.length != 2) {
                            this.setProperty(isSolace? "Host" : "serverUrl", val); // for tibco
                        } else {
                            throw new IllegalArgumentException("Failed to parse broker url: " + entry.getValue());
                        }
                    }
                }
                SSLContextService sc = context.getProperty(SSL_CONTEXT_SERVICE).asControllerService(SSLContextService.class);
                if (sc != null) {
                    SSLContext ssl = sc.createSSLContext(ClientAuth.NONE);
                    this.setProperty("sSLSocketFactory", ssl.getSocketFactory());
                }
            } // ignore 'else', since it's the only non-dynamic property that is relevant to CF configuration
        }
    }
}
 
Example 50
Project: habpanelviewer   File: ConnectionUtil.java   Source Code and License 5 votes vote down vote up
public static synchronized void initialize(Context ctx) throws GeneralSecurityException, IOException {
    localTrustStoreFile = new File(ctx.getFilesDir(), "localTrustStore.bks");
    if (!localTrustStoreFile.exists()) {
        try (InputStream in = ctx.getResources().openRawResource(R.raw.mytruststore)) {
            copy(in, localTrustStoreFile);
        }
    }

    System.setProperty("javax.net.ssl.trustStore", localTrustStoreFile.getAbsolutePath());

    SSLContext sslContext = createSslContext();
    HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
}
 
Example 51
Project: springboot-shiro-cas-mybatis   File: FileTrustStoreSslSocketFactory.java   Source Code and License 5 votes vote down vote up
/**
 * Gets the trusted ssl context.
 *
 * @param trustStoreFile the trust store file
 * @param trustStorePassword the trust store password
 * @param trustStoreType the trust store type
 * @return the trusted ssl context
 */
private static SSLContext getTrustedSslContext(final File trustStoreFile, final String trustStorePassword,
                                        final String trustStoreType) {
    try {

        if (!trustStoreFile.exists() || !trustStoreFile.canRead()) {
            throw new FileNotFoundException("Truststore file cannot be located at "
                + trustStoreFile.getCanonicalPath());
        }

        final KeyStore casTrustStore = KeyStore.getInstance(trustStoreType);
        final char[] trustStorePasswordCharArray = trustStorePassword.toCharArray();

        try (FileInputStream casStream = new FileInputStream(trustStoreFile)) {
            casTrustStore.load(casStream, trustStorePasswordCharArray);
        }

        final String defaultAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
        final X509KeyManager customKeyManager = getKeyManager("PKIX", casTrustStore, trustStorePasswordCharArray);
        final X509KeyManager jvmKeyManager = getKeyManager(defaultAlgorithm, null, null);
        final X509TrustManager customTrustManager = getTrustManager("PKIX", casTrustStore);
        final X509TrustManager jvmTrustManager = getTrustManager(defaultAlgorithm, null);

        final KeyManager[] keyManagers = {
                new CompositeX509KeyManager(Arrays.asList(jvmKeyManager, customKeyManager))
        };
        final TrustManager[] trustManagers = {
                new CompositeX509TrustManager(Arrays.asList(jvmTrustManager, customTrustManager))
        };

        final SSLContext context = SSLContexts.custom().useSSL().build();
        context.init(keyManagers, trustManagers, null);
        return context;

    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        throw new RuntimeException(e);
    }
}
 
Example 52
Project: java-coap   File: DeviceEmulator.java   Source Code and License 5 votes vote down vote up
private CoapTransport createTransport(String keystoreFile, URI uri) {
    CoapTransport coapTransport;

    if (uri.getScheme().equals("coap")) {
        coapTransport = new DatagramSocketTransport(0);
    } else if (uri.getScheme().equals("coaps")) {

        SSLContext sslContext = sslContextFromKeystore(keystoreFile, "secret".toCharArray());

        coapTransport = new SSLSocketClientTransport(new InetSocketAddress(uri.getHost(), uri.getPort()), sslContext.getSocketFactory(), false);
    } else {
        throw new IllegalArgumentException("Protocol not supported: " + uri.getScheme());
    }
    return coapTransport;
}
 
Example 53
Project: jdk8u-jdk   File: ConnectorBootstrap.java   Source Code and License 5 votes vote down vote up
private SslServerSocket(int port,
                        SSLContext ctx,
                        String[] enabledCipherSuites,
                        String[] enabledProtocols,
                        boolean needClientAuth) throws IOException {
    super(port);
    this.enabledProtocols = enabledProtocols;
    this.enabledCipherSuites = enabledCipherSuites;
    this.needClientAuth = needClientAuth;
    this.context = ctx;
}
 
Example 54
Project: ats-framework   File: InetSmtpConnection.java   Source Code and License 5 votes vote down vote up
/**
 * Returns a configured SSLSocketFactory to use in creating new SSL
 * sockets.
 * @param tm an optional trust manager to use
 */
protected SSLSocketFactory getSSLSocketFactory(
                                                TrustManager tm ) throws GeneralSecurityException {

    if (tm == null) {
        tm = new EmptyX509TrustManager();
    }
    SSLContext context = SSLContext.getInstance("TLS");
    TrustManager[] trust = new TrustManager[]{ tm };
    context.init(null, trust, null);
    return context.getSocketFactory();
}
 
Example 55
Project: li-android-sdk-core   File: LiRestv2ClientTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testValidateResponse() throws Exception {
    context = Mockito.mock(Activity.class);
    PowerMockito.mockStatic(LiClientManager.class);
    LiClientManager liClientManager = PowerMockito.mock(LiClientManager.class);

    PowerMockito.mockStatic(SSLContext.class);
    SSLContext sslContext = PowerMockito.mock(SSLContext.class);
    when(sslContext.getInstance("SSL")).thenReturn(sslContext);
    Mockito.doNothing().when(sslContext).init(isA(KeyManager[].class), isA(TrustManager[].class), isA(SecureRandom.class));
    SSLSocketFactory socketFactory = mock(SSLSocketFactory.class);
    when(sslContext.getSocketFactory()).thenReturn(socketFactory);

    PowerMockito.mockStatic(Platform.class);
    Platform platform = PowerMockito.mock(Platform.class);
    X509TrustManager trustManager = mock(X509TrustManager.class);
    when(platform.trustManager(socketFactory)).thenReturn(trustManager);
    BDDMockito.given(Platform.get()).willReturn(platform);

    BDDMockito.given(SSLContext.getInstance("SSL")).willReturn(sslContext);

    LiRestv2Client liRestv2Client = LiRestv2Client.getInstance();
    final LiBaseResponse liBaseResponse = mock(LiBaseResponse.class);
    when(liBaseResponse.getHttpCode()).thenReturn(200);
    LiRestv2Client liRestv2ClientSpy = spy(LiRestv2Client.class);
    doReturn(liBaseResponse).when(liRestv2ClientSpy).processSync(isA(LiBaseRestRequest.class));

    LiRestV2Request liBaseRestRequest = new LiRestV2Request(context, liql, "message");
    liBaseRestRequest.addQueryParam("test");

    LiBaseResponse liBaseResponse1 = liRestv2ClientSpy.processSync(liBaseRestRequest);

    Assert.assertEquals(200, liBaseResponse1.getHttpCode());
    PowerMockito.verifyStatic();
}
 
Example 56
Project: ats-framework   File: HttpClient.java   Source Code and License 5 votes vote down vote up
private static void initSSL() throws RuntimeException /* GeneralSecurityException */ {

        try {
            sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, new TrustManager[]{ new DefaultTrustManager() }, null);
        } catch (GeneralSecurityException e) {
            throw new RuntimeException("Error setting trust-all trust manager", e);
        }
    }
 
Example 57
Project: MinimalFTP   File: FTPConnection.java   Source Code and License 5 votes vote down vote up
public void enableSSL(SSLContext context) throws IOException {
    SSLSocketFactory factory = context.getSocketFactory();
    con = factory.createSocket(con, con.getInetAddress().getHostAddress(), con.getPort(), true);
    ((SSLSocket)con).setUseClientMode(false);

    reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
    writer = new BufferedWriter(new OutputStreamWriter(con.getOutputStream()));
}
 
Example 58
Project: in-store-api-java-sdk   File: NetworkUtilities.java   Source Code and License 5 votes vote down vote up
public static OkHttpClient.Builder getClient(SatispayContext satispayContext) {
    OkHttpClient.Builder okHttpClientBuilder;
    okHttpClientBuilder = new OkHttpClient.Builder();

    // ==> the SSL context is build only in environments different from PROD / STAGING, where the server cert is self signed
    String serverCert = satispayContext.getServerCert();
    if (serverCert != null) {
        try {
            String keyStoreType = KeyStore.getDefaultType();
            KeyStore keyStore;
            keyStore = KeyStore.getInstance(keyStoreType);
            keyStore.load(null, null);
            keyStore.setCertificateEntry("ca", CryptoUtils.certificateX509(serverCert));

            String trustManagerDefaultAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(trustManagerDefaultAlgorithm);
            trustManagerFactory.init(keyStore);

            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
            okHttpClientBuilder.sslSocketFactory(sslSocketFactory);
        } catch (Exception e) {
            ProtoLogger.error("!!! Error generating TLS context !!!");
        }
    }
    okHttpClientBuilder.connectTimeout(10, TimeUnit.SECONDS);
    okHttpClientBuilder.writeTimeout(10, TimeUnit.SECONDS);
    okHttpClientBuilder.readTimeout(30, TimeUnit.SECONDS);
    return okHttpClientBuilder;
}
 
Example 59
Project: FirefoxData-android   File: SSLSocketFactory.java   Source Code and License 5 votes vote down vote up
/**
 * @since 4.3
 */
public SSLSocketFactory(
        final SSLContext sslContext,
        final String[] supportedProtocols,
        final String[] supportedCipherSuites,
        final X509HostnameVerifier hostnameVerifier) {
    this(Args.notNull(sslContext, "SSL context").getSocketFactory(),
            supportedProtocols, supportedCipherSuites, hostnameVerifier);
}
 
Example 60
Project: iothub   File: MqttSslHandlerProvider.java   Source Code and License 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);
    }
}