java.security.KeyManagementException Java Examples

The following examples show how to use java.security.KeyManagementException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HttpUtil.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the http client.
 *
 * @return the http client
 */
private static CloseableHttpClient getHttpClient() {
    CloseableHttpClient httpClient = null;
    try {
        httpClient = HttpClientBuilder.create().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                .setSSLContext(new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                    @Override
                    public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                        return true;
                    }
                }).build()).build();
    } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
        LOGGER.error("Error getting getHttpClient " , e);
    }
    return httpClient;
}
 
Example #2
Source File: HTTPSTrustManager.java    From styT with Apache License 2.0 6 votes vote down vote up
public static void allowAllSSL() {
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        @Override
        public boolean verify(String arg0, SSLSession arg1) {
            return true;
        }
    });

    SSLContext sslContext = null;
    if (trustManagers == null) {
        trustManagers = new TrustManager[]{new HTTPSTrustManager()};
    }

    try {
        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustManagers, new SecureRandom());
    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        e.printStackTrace();
    }
    if (sslContext != null) {
        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
    }
}
 
Example #3
Source File: AndroidSslSocketFactoryFactory.java    From PresencePublisher with MIT License 6 votes vote down vote up
SSLSocketFactory getSslSocketFactory(@Nullable String clientCertAlias) {
    try {
        SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        KeyStore androidCAStore = KeyStore.getInstance("AndroidCAStore");
        if (androidCAStore == null) {
            HyperLog.w(TAG, "Unable to load CA keystore");
            return null;
        }
        androidCAStore.load(null);
        trustManagerFactory.init(androidCAStore);
        KeyManager[] keyManagers = null;
        if (clientCertAlias != null) {
            keyManagers = getClientKeyManagers(clientCertAlias);
        }
        sslContext.init(keyManagers, trustManagerFactory.getTrustManagers(), null);
        return sslContext.getSocketFactory();
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException | CertificateException | IOException e) {
        HyperLog.w(TAG, "Unable to get socket factory", e);
        return null;
    }
}
 
Example #4
Source File: PushServiceSocket.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
private static OkHttpClient createConnectionClient(SignalUrl url, List<Interceptor> interceptors, Optional<Dns> dns) {
  try {
    TrustManager[] trustManagers = BlacklistingTrustManager.createFor(url.getTrustStore());

    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, trustManagers, null);

    OkHttpClient.Builder builder = new OkHttpClient.Builder()
                                                   .sslSocketFactory(new Tls12SocketFactory(context.getSocketFactory()), (X509TrustManager)trustManagers[0])
                                                   .connectionSpecs(url.getConnectionSpecs().or(Util.immutableList(ConnectionSpec.RESTRICTED_TLS)))
                                                   .dns(dns.or(Dns.SYSTEM));

    builder.sslSocketFactory(new Tls12SocketFactory(context.getSocketFactory()), (X509TrustManager)trustManagers[0])
           .connectionSpecs(url.getConnectionSpecs().or(Util.immutableList(ConnectionSpec.RESTRICTED_TLS)))
           .build();

    for (Interceptor interceptor : interceptors) {
      builder.addInterceptor(interceptor);
    }

    return builder.build();
  } catch (NoSuchAlgorithmException | KeyManagementException e) {
    throw new AssertionError(e);
  }
}
 
Example #5
Source File: HttpUtil.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the http client.
 *
 * @return the http client
 */
private static CloseableHttpClient getHttpClient() {
    CloseableHttpClient httpClient = null;
    try {
        httpClient = HttpClientBuilder.create().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                .setSSLContext(new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                    @Override
                    public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                        return true;
                    }
                }).build()).build();
    } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
        LOGGER.error("Error getting getHttpClient " , e);
    }
    return httpClient;
}
 
Example #6
Source File: SSLUtils.java    From ssltest with Apache License 2.0 6 votes vote down vote up
/**
     * Creates an SSLSocketFactory that supports only the specified protocols
     * and ciphers.
     */
    public static SSLSocketFactory getSSLSocketFactory(String protocol,
                                                       String[] sslEnabledProtocols,
                                                       String[] sslCipherSuites,
                                                       SecureRandom random,
                                                       TrustManager[] tms,
                                                       KeyManager[] kms)
        throws NoSuchAlgorithmException, KeyManagementException
    {
        SSLContext sc = SSLContext.getInstance(protocol);

//        System.out.println("Wanted protocol: " + protocol);
//        System.out.println("Got protocol:    " + sc.getProtocol());

        sc.init(kms, tms, random);

        SSLSocketFactory sf = sc.getSocketFactory();

        if(null != sslEnabledProtocols
           || null != sslCipherSuites)
            sf = new CustomSSLSocketFactory(sf,
                                            sslEnabledProtocols,
                                            sslCipherSuites);

        return sf;
    }
 
Example #7
Source File: HttpClientConfig.java    From Pixiv-Illustration-Collection-Backend with Apache License 2.0 6 votes vote down vote up
@Bean
    @Primary
    @Autowired
    public HttpClient httpClientWithOutProxy(TrustManager[] trustAllCertificates, ExecutorService httpclientExecutorService) throws NoSuchAlgorithmException, KeyManagementException {
        SSLParameters sslParams = new SSLParameters();
        sslParams.setEndpointIdentificationAlgorithm("");
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCertificates, new SecureRandom());
        return HttpClient.newBuilder()
                .version(HttpClient.Version.HTTP_1_1)
//                .sslParameters(sslParams)
//                .sslContext(sc)
                .connectTimeout(Duration.ofSeconds(30))
              //          .proxy(ProxySelector.of(new InetSocketAddress("127.0.0.1", 8888)))
                .executor(httpclientExecutorService)
                .followRedirects(HttpClient.Redirect.NEVER)
                .build();
    }
 
Example #8
Source File: HttpClientSteps.java    From yaks with Apache License 2.0 6 votes vote down vote up
/**
 * Get secure http client implementation with trust all strategy and noop host name verifier.
 * @return
 */
private org.apache.http.client.HttpClient sslClient() {
    try {
        SSLContext sslcontext = SSLContexts
                .custom()
                .loadTrustMaterial(TrustAllStrategy.INSTANCE)
                .build();

        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(
                sslcontext, NoopHostnameVerifier.INSTANCE);

        return HttpClients
                .custom()
                .setSSLSocketFactory(sslSocketFactory)
                .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                .build();
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
        throw new CitrusRuntimeException("Failed to create http client for ssl connection", e);
    }
}
 
Example #9
Source File: SslContextFactory.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a SSLContext instance using the given information.
 *
 * @param truststore the full path to the truststore
 * @param truststorePasswd the truststore password
 * @param truststoreType the type of truststore (e.g., PKCS12, JKS)
 * @param protocol the protocol to use for the SSL connection
 *
 * @return a SSLContext instance
 * @throws java.security.KeyStoreException if any issues accessing the keystore
 * @throws java.io.IOException for any problems loading the keystores
 * @throws java.security.NoSuchAlgorithmException if an algorithm is found to be used but is unknown
 * @throws java.security.cert.CertificateException if there is an issue with the certificate
 * @throws java.security.UnrecoverableKeyException if the key is insufficient
 * @throws java.security.KeyManagementException if unable to manage the key
 */
public static SSLContext createTrustSslContext(
        final String truststore, final char[] truststorePasswd, final String truststoreType, final String protocol)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException,
        UnrecoverableKeyException, KeyManagementException {

    // prepare the truststore
    final KeyStore trustStore = KeyStoreUtils.getTrustStore(truststoreType);
    try (final InputStream trustStoreStream = new FileInputStream(truststore)) {
        trustStore.load(trustStoreStream, truststorePasswd);
    }
    final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(trustStore);

    // initialize the ssl context
    final SSLContext ctx = SSLContext.getInstance(protocol);
    ctx.init(new KeyManager[0], trustManagerFactory.getTrustManagers(), new SecureRandom());

    return ctx;

}
 
Example #10
Source File: SecureSslContextFactory.java    From openAGV with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an instance of {@link SSLContext} for the client.
 *
 * @return The ssl context.
 * @throws IllegalStateException If the creation of the ssl context fails.
 */
public SSLContext createClientContext()
    throws IllegalStateException {
  SSLContext context = null;

  try {
    KeyStore ts = KeyStore.getInstance(sslParameterSet.getKeystoreType());
    ts.load(new FileInputStream(sslParameterSet.getTruststoreFile()),
            sslParameterSet.getTruststorePassword().toCharArray());
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(KEY_TRUST_MANAGEMENT_ALGORITHM);
    tmf.init(ts);

    context = SSLContext.getInstance(SSL_CONTEXT_PROTOCOL);
    context.init(null, tmf.getTrustManagers(), null);
  }
  catch (NoSuchAlgorithmException | KeyStoreException | CertificateException | IOException
             | KeyManagementException ex) {
    throw new IllegalStateException("Error creating the client's ssl context", ex);
  }

  return context;
}
 
Example #11
Source File: ClientReceive1.java    From java-study with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args)
    throws java.io.IOException,java.lang.InterruptedException, TimeoutException, KeyManagementException, NoSuchAlgorithmException, URISyntaxException{
        ConnectionFactory factory=new ConnectionFactory();
//        factory.setHost("localhost");
//        factory.setVirtualHost("my_mq");
//        factory.setUsername("zhxia");
//        factory.setPassword("123456");
        factory.setUri("amqp://guest:[email protected]:5672");//获取url
        Connection connection=factory.newConnection();
        Channel channel=connection.createChannel();
        channel.queueDeclare(queue_name, durable, false, false, null);
        System.out.println("Wait for message");
        channel.basicQos(1); //消息分发处理
        QueueingConsumer consumer=new QueueingConsumer(channel);
        channel.basicConsume(queue_name, autoAck, consumer);
        while(true){
            Thread.sleep(500);
            QueueingConsumer.Delivery deliver=consumer.nextDelivery();
            String message=new String(deliver.getBody());
            System.out.println("Message received:"+message);
            channel.basicAck(deliver.getEnvelope().getDeliveryTag(), false);
        }
    }
 
Example #12
Source File: GetHTTP.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
private SSLContext createSSLContext(final SSLContextService service)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, KeyManagementException, UnrecoverableKeyException {

    final SSLContextBuilder sslContextBuilder = new SSLContextBuilder();

    if (StringUtils.isNotBlank(service.getTrustStoreFile())) {
        final KeyStore truststore = KeyStoreUtils.getTrustStore(service.getTrustStoreType());
        try (final InputStream in = new FileInputStream(new File(service.getTrustStoreFile()))) {
            truststore.load(in, service.getTrustStorePassword().toCharArray());
        }
        sslContextBuilder.loadTrustMaterial(truststore, new TrustSelfSignedStrategy());
    }

    if (StringUtils.isNotBlank(service.getKeyStoreFile())){
        final KeyStore keystore = KeyStoreUtils.getKeyStore(service.getKeyStoreType());
        try (final InputStream in = new FileInputStream(new File(service.getKeyStoreFile()))) {
            keystore.load(in, service.getKeyStorePassword().toCharArray());
        }
        sslContextBuilder.loadKeyMaterial(keystore, service.getKeyStorePassword().toCharArray());
    }

    sslContextBuilder.useProtocol(service.getSslAlgorithm());

    return sslContextBuilder.build();
}
 
Example #13
Source File: DownloadCartridgeTask.java    From WhereYouGo with GNU General Public License v3.0 6 votes vote down vote up
private boolean init() {
    try {
        System.setProperty("http.keepAlive", "false");
        httpClient = new OkHttpClient.Builder()
                .sslSocketFactory(new TLSSocketFactory())
                .cookieJar(new NonPersistentCookieJar())
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .build();
    } catch (KeyManagementException | NoSuchAlgorithmException e) {
        Logger.e(TAG, "init()", e);
        errorMessage = e.getMessage();
    }
    if (httpClient == null)
        publishProgress(new Progress(Task.INIT, State.FAIL, errorMessage));
    return httpClient != null;
}
 
Example #14
Source File: GerritChecksApiBuilder.java    From gerrit-code-review-plugin with Apache License 2.0 6 votes vote down vote up
public GerritChecksApiBuilder allowInsecureHttps() {
  try {
    SSLContext sslContext =
        new SSLContextBuilder()
            .loadTrustMaterial(
                null,
                new TrustStrategy() {
                  public boolean isTrusted(final X509Certificate[] chain, String authType)
                      throws CertificateException {
                    return true;
                  }
                })
            .build();
    SSLConnectionSocketFactory sslsf =
        new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());
    clientBuilder.setSSLSocketFactory(sslsf);
  } catch (KeyStoreException | KeyManagementException | NoSuchAlgorithmException e) {
    LOGGER.log(Level.WARNING, "Could not disable SSL verification.", e);
  }
  return this;
}
 
Example #15
Source File: DockerServerCredentialsSSLConfig.java    From docker-swarm-plugin with MIT License 6 votes vote down vote up
@Override
public SSLContext getSSLContext()
        throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException {

    try {
        final KeyStore keyStore = CertificateUtils.createKeyStore(credentials.getClientKey(),
                credentials.getClientCertificate());
        final KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, "docker".toCharArray());
        final KeyStore trustStore = CertificateUtils.createTrustStore(credentials.getServerCaCertificate());
        final TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);

        final SSLContext context = SSLContext.getInstance("TLS");
        context.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
        return context;
    } catch (CertificateException | InvalidKeySpecException | IOException e) {
        throw new KeyStoreException("Can't build keystore from provided client key/certificate", e);
    }
}
 
Example #16
Source File: TLSClientPropertyTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * The parameter passed is the user enforced protocol. Does not catch
 * NoSuchAlgorithmException, WrongProperty test will use it.
 */
public void test(String expectedContextProto,
        String[] expectedDefaultProtos) throws NoSuchAlgorithmException {

    SSLContext context = null;
    try {
        if (expectedContextProto != null) {
            context = SSLContext.getInstance(expectedContextProto);
            context.init(null, null, null);
        } else {
            context = SSLContext.getDefault();
        }
        printContextDetails(context);
    } catch (KeyManagementException ex) {
        error(null, ex);
    }

    validateContext(expectedContextProto, expectedDefaultProtos, context);
}
 
Example #17
Source File: SSLEngineFactory.java    From NetBare with MIT License 6 votes vote down vote up
private TrustManager[] getClientTrustManager() {
    try {
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(
                TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init((KeyStore) null);
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
        if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
            throw new KeyManagementException("Unexpected default trust managers:"
                    + Arrays.toString(trustManagers));
        }
        return trustManagers;
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
        NetBareLog.wtf(e);
    }
    return null;
}
 
Example #18
Source File: HttpClientWrapper.java    From TrackRay with GNU General Public License v3.0 6 votes vote down vote up
public static void enabledSSL() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    SSLContextBuilder builder = new SSLContextBuilder();
    builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(builder.build(), NoopHostnameVerifier.INSTANCE);
    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", new PlainConnectionSocketFactory())
            .register("https", sslConnectionSocketFactory)
            .build();

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
    cm.setMaxTotal(100);
    client = HttpClients.custom()
            .setSSLSocketFactory(sslConnectionSocketFactory)
            .setConnectionManager(cm)
            .build();
}
 
Example #19
Source File: HttpRequestProcessor.java    From protect with MIT License 6 votes vote down vote up
public HttpRequestProcessor(final int serverIndex, final ServerConfiguration serverConfig,
		final AccessEnforcement accessEnforcement, final ConcurrentMap<String, ApvssShareholder> shareholders,
		final List<X509Certificate> caCerts, final X509Certificate hostCert, final PrivateKey privateKey,
		final KeyLoader clientKeys, final KeyLoader serverKeys)
		throws IOException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException,
		UnrecoverableKeyException, CertificateException {

	final int httpListenPort = CommonConfiguration.BASE_HTTP_PORT + serverIndex;
	this.server = HttpsServer.create(new InetSocketAddress(httpListenPort), 0);

	setupTls(caCerts, hostCert, privateKey, serverIndex);

	System.out.println("HTTPS server listening on port: " + httpListenPort);

	addHandlers(serverIndex, serverConfig, accessEnforcement, shareholders, clientKeys, serverKeys, caCerts, hostCert, privateKey);

	System.out.println("Ready to process requests.");

	// this.server.setExecutor(Executors.newFixedThreadPool(NUM_PROCESSING_THREADS));
}
 
Example #20
Source File: HttpEventPublisher.java    From DataflowTemplates with Apache License 2.0 5 votes vote down vote up
/**
 * Validates and builds a {@link HttpEventPublisher} object.
 *
 * @return {@link HttpEventPublisher}
 */
public HttpEventPublisher build()
    throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {

  checkNotNull(token(), "Authentication token needs to be specified via withToken(token).");
  checkNotNull(genericUrl(), "URL needs to be specified via withUrl(url).");

  if (disableCertificateValidation() == null) {
    LOG.info("Certificate validation disabled: {}", DEFAULT_DISABLE_CERTIFICATE_VALIDATION);
    setDisableCertificateValidation(DEFAULT_DISABLE_CERTIFICATE_VALIDATION);
  }

  if (maxElapsedMillis() == null) {
    LOG.info(
        "Defaulting max backoff time to: {} milliseconds ",
        ExponentialBackOff.DEFAULT_MAX_ELAPSED_TIME_MILLIS);
    setMaxElapsedMillis(ExponentialBackOff.DEFAULT_MAX_ELAPSED_TIME_MILLIS);
  }

  CloseableHttpClient httpClient =
      getHttpClient(DEFAULT_MAX_CONNECTIONS, disableCertificateValidation());

  setTransport(new ApacheHttpTransport(httpClient));
  setRequestFactory(transport().createRequestFactory());

  return autoBuild();
}
 
Example #21
Source File: JSSESSLContext.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
public void init(KeyManager[] kms, TrustManager[] tms, SecureRandom sr)
        throws KeyManagementException {
    this.kms = kms;
    this.tms = tms;
    context.init(kms, tms, sr);
}
 
Example #22
Source File: HttpRequest.java    From mica with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static void disableSslValidation(OkHttpClient.Builder builder) {
	try {
		X509TrustManager disabledTrustManager = DisableValidationTrustManager.INSTANCE;
		TrustManager[] trustManagers = new TrustManager[]{disabledTrustManager};
		SSLContext sslContext = SSLContext.getInstance("SSL");
		sslContext.init(null, trustManagers, Holder.SECURE_RANDOM);
		SSLSocketFactory disabledSslSocketFactory = sslContext.getSocketFactory();
		builder.sslSocketFactory(disabledSslSocketFactory, disabledTrustManager);
		builder.hostnameVerifier(TrustAllHostNames.INSTANCE);
	} catch (NoSuchAlgorithmException | KeyManagementException e) {
		throw Exceptions.unchecked(e);
	}
}
 
Example #23
Source File: TLSConfig.java    From data-highway with Apache License 2.0 5 votes vote down vote up
public static SSLContext trustAllSSLContext() {
  try {
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, trustAllTrustManager(), new SecureRandom());
    return sslContext;
  } catch (NoSuchAlgorithmException | KeyManagementException e) {
    throw new RuntimeException(e);
  }
}
 
Example #24
Source File: WebSocketConnection.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
private Pair<SSLSocketFactory, X509TrustManager> createTlsSocketFactory(TrustStore trustStore) {
  try {
    SSLContext     context       = SSLContext.getInstance("TLS");
    TrustManager[] trustManagers = BlacklistingTrustManager.createFor(trustStore);
    context.init(null, trustManagers, null);

    return new Pair<>(context.getSocketFactory(), (X509TrustManager)trustManagers[0]);
  } catch (NoSuchAlgorithmException | KeyManagementException e) {
    throw new AssertionError(e);
  }
}
 
Example #25
Source File: SSLHandlerFactory.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
public SSLHandlerFactory(InboundWebsocketSSLConfiguration sslConfiguration) {
    String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
    if (algorithm == null) {
        algorithm = "SunX509";
    }
    try {
        KeyStore keyStore = getKeyStore(sslConfiguration.getKeyStore(), sslConfiguration.getKeyStorePass());
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(algorithm);
        keyManagerFactory.init(keyStore, sslConfiguration.getCertPass() != null ?
                sslConfiguration.getCertPass().toCharArray() :
                sslConfiguration.getKeyStorePass().toCharArray());
        KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();
        TrustManager[] trustManagers = null;
        if (sslConfiguration.getTrustStore() != null) {
            this.needClientAuth = true;
            KeyStore trustStore = getKeyStore(sslConfiguration.getTrustStore(),
                                              sslConfiguration.getTrustStorePass());
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(algorithm);
            trustManagerFactory.init(trustStore);
            trustManagers = trustManagerFactory.getTrustManagers();
        }
        serverContext = SSLContext.getInstance(protocol);
        serverContext.init(keyManagers, trustManagers, null);
        cipherSuites = sslConfiguration.getCipherSuites();
        sslProtocols = sslConfiguration.getSslProtocols();
    } catch (UnrecoverableKeyException | KeyManagementException | NoSuchAlgorithmException | KeyStoreException | IOException ex) {
        throw new IllegalArgumentException("Failed to initialize the server side SSLContext", ex);
    }
}
 
Example #26
Source File: SwirldsAdaptor.java    From exo-demo with MIT License 5 votes vote down vote up
private void setupSecuredSocket() {		
	ClientConfig config = ExoConfig.getConfig().clientConfig;
	
	try {
		SecureRandom secureRandom = new SecureRandom();
		secureRandom.nextInt();
		
		KeyStore clientKeyStore = KeyStore.getInstance("JKS");
		clientKeyStore.load(new FileInputStream(config.clientKeystore.path), config.clientKeystore.password.toCharArray());
		
		KeyStore serverKeyStore = KeyStore.getInstance("JKS");
		serverKeyStore.load(new FileInputStream(config.serverKeystore.path), config.serverKeystore.password.toCharArray());
		
		TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
		tmf.init(serverKeyStore);
		
		KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
		kmf.init(clientKeyStore, "client".toCharArray());
		
		SSLContext sslContext = SSLContext.getInstance("TLS");
		sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), secureRandom);
		
		SSLSocketFactory socketFactory = sslContext.getSocketFactory();
		InetSocketAddress destination = (InetSocketAddress) SwirldsAdaptor.nodeRouter.getNode();

		System.out.println("Attempting to create a connection to " + destination.getHostName() + ":" + destination.getPort());
		this.socket = socketFactory.createSocket(destination.getHostName(), destination.getPort());  //new Socket(HOST, PORT);
	} catch (	IOException | 
				KeyStoreException | 
				NoSuchAlgorithmException | 
				CertificateException | 
				UnrecoverableKeyException | 
				KeyManagementException e) {
		e.printStackTrace();
		throw new IllegalStateException("An error has occurred while configuring a secured socket:  " + e.getMessage());
	}
}
 
Example #27
Source File: TestListenTCP.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testTLSClienAuthRequiredAndClientCertNotProvided() throws InitializationException, IOException, InterruptedException,
        UnrecoverableKeyException, CertificateException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {

    runner.setProperty(ListenTCP.CLIENT_AUTH, SSLContextService.ClientAuth.REQUIRED.name());
    configureProcessorSslContextService();

    final List<String> messages = new ArrayList<>();
    messages.add("This is message 1\n");
    messages.add("This is message 2\n");
    messages.add("This is message 3\n");
    messages.add("This is message 4\n");
    messages.add("This is message 5\n");

    // Make an SSLContext that only has the trust store, this should not work since the processor has client auth REQUIRED
    final SSLContext clientSslContext = SslContextFactory.createTrustSslContext(
            "src/test/resources/localhost-ts.jks",
            "localtest".toCharArray(),
            "jks",
            "TLS");

    try {
        runTCP(messages, messages.size(), clientSslContext);
        Assert.fail("Should have thrown exception");
    } catch (Exception e) {

    }
}
 
Example #28
Source File: ApnsPushService.java    From p2 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public ApnsPushService() {
    final GsonBuilder gsonBuilder = new GsonBuilder();
    Adapter.register(gsonBuilder);
    gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES);

    final SSLContext sslContext;
    try {
        sslContext = SSLContext.getInstance("TLSv1.2");
        sslContext.init(new KeyManager[]{new ClientCertificateKeyManager()}, null, null);
    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        throw new AssertionError(e);
    }

    final X509TrustManager trustManager = TrustManager.getDefault();
    if (trustManager == null) {
        throw new AssertionError("Unable to find default trust manager");
    }
    final OkHttpClient.Builder okHttpBuilder = new OkHttpClient.Builder();
    okHttpBuilder.sslSocketFactory(sslContext.getSocketFactory(), trustManager);

    ApnsConfiguration configuration = Configuration.getInstance().getApnsConfiguration();

    final Retrofit.Builder retrofitBuilder = new Retrofit.Builder();
    if (configuration != null && configuration.isSandbox()) {
        retrofitBuilder.baseUrl(SANDBOX_BASE_URL);
    } else {
        retrofitBuilder.baseUrl(BASE_URL);
    }
    retrofitBuilder.addConverterFactory(GsonConverterFactory.create(gsonBuilder.create()));
    retrofitBuilder.client(okHttpBuilder.build());

    final Retrofit retrofit = retrofitBuilder.build();

    this.httpInterface = retrofit.create(ApnsHttpInterface.class);
}
 
Example #29
Source File: RecoverHandler.java    From protect with MIT License 5 votes vote down vote up
public void configureHttps(final HttpsURLConnection httpsConnection, final int remoteServerId, final int ourIndex)
		throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException,
		UnrecoverableKeyException, KeyManagementException {

	// Configure SSL context
	final SSLContext sslContext = SSLContext.getInstance(CommonConfiguration.TLS_VERSION);

	// Create in-memory key store
	final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
	final char[] password = "password".toCharArray();
	keyStore.load(null, password);

	// Add the CA certificate for the server
	keyStore.setCertificateEntry("ca-" + remoteServerId, this.caCerts.get(remoteServerId - 1));

	// Add certificate and private key for the server
	final X509Certificate ourCaCert = caCerts.get(ourIndex - 1);
	keyStore.setKeyEntry("host", this.privateKey, password, new X509Certificate[] { hostCert, ourCaCert });

	// Make Key Manager Factory
	final KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
	kmf.init(keyStore, password);

	// Setup the trust manager factory
	final TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
	tmf.init(keyStore);

	// Initialize the context
	sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());

	// Get the socket factory from the context
	httpsConnection.setSSLSocketFactory(sslContext.getSocketFactory());
}
 
Example #30
Source File: HttpClientUtils.java    From halo with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Creates https client.
 *
 * @param timeout connection timeout (ms)
 * @return https client
 * @throws KeyStoreException        key store exception
 * @throws NoSuchAlgorithmException no such algorithm exception
 * @throws KeyManagementException   key management exception
 */
@NonNull
public static CloseableHttpClient createHttpsClient(int timeout) throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    SSLContext sslContext = new SSLContextBuilder()
        .loadTrustMaterial(null, (certificate, authType) -> true)
        .build();

    return HttpClients.custom()
        .setSSLContext(sslContext)
        .setSSLHostnameVerifier(new NoopHostnameVerifier())
        .setDefaultRequestConfig(getRequestConfig(timeout))
        .build();
}