Java Code Examples for org.apache.http.ssl.SSLContextBuilder#loadKeyMaterial()

The following examples show how to use org.apache.http.ssl.SSLContextBuilder#loadKeyMaterial() . 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: GetHTTP.java    From nifi with Apache License 2.0 8 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 2
Source File: SSLSessionStrategyFactory.java    From apiman with Apache License 2.0 6 votes vote down vote up
private static SSLContextBuilder loadKeyMaterial(SSLContextBuilder builder, File file, char[] ksp,
        char[] kp, PrivateKeyStrategy privateKeyStrategy) throws NoSuchAlgorithmException,
                KeyStoreException, UnrecoverableKeyException, CertificateException, IOException {
    Args.notNull(file, "Keystore file"); //$NON-NLS-1$
    final KeyStore identityStore = KeyStore.getInstance(KeyStore.getDefaultType());
    final FileInputStream instream = new FileInputStream(file);
    try {
        identityStore.load(instream, ksp);
    } finally {
        instream.close();
    }
    return builder.loadKeyMaterial(identityStore, kp, privateKeyStrategy);
}
 
Example 3
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 4
Source File: DefaultConsulConfigGateway.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private SSLConnectionSocketFactory createFactoryFromAgentConfig(ConsulConfig.AgentConfig agentConfig) {
    try {
        SSLContextBuilder sslContextBuilder = SSLContexts.custom();
        if (agentConfig.trustStore.isPresent()) {
            sslContextBuilder = sslContextBuilder
                    .loadTrustMaterial(readStore(agentConfig.trustStore.get(), agentConfig.trustStorePassword), null);
        } else if (agentConfig.trustCerts) {
            sslContextBuilder = sslContextBuilder.loadTrustMaterial(TrustAllStrategy.INSTANCE);
        }
        if (agentConfig.keyStore.isPresent()) {
            String keyPassword = agentConfig.keyPassword.orElse(agentConfig.keyStorePassword.orElse(""));
            sslContextBuilder = sslContextBuilder.loadKeyMaterial(
                    readStore(agentConfig.keyStore.get(), agentConfig.keyStorePassword), keyPassword.toCharArray());
        }
        return new SSLConnectionSocketFactory(sslContextBuilder.build(), NoopHostnameVerifier.INSTANCE);
    } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException | IOException | CertificateException
            | UnrecoverableKeyException e) {
        throw new RuntimeException(e);
    }
}
 
Example 5
Source File: SecurityUtils.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
static SSLConnectionSocketFactory createSocketFactory(Path truststoreFile, Path keystoreFile, String password)
        throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, CertificateException,
        IOException, UnrecoverableKeyException {
    final char[] pwd = password.toCharArray();
    SSLContextBuilder sslcontextBuilder = SSLContexts.custom()//
            .loadTrustMaterial(truststoreFile.toFile(), pwd, TrustSelfSignedStrategy.INSTANCE)//
    ;
    if (keystoreFile != null) {
        sslcontextBuilder.loadKeyMaterial(keystoreFile.toFile(), pwd, pwd);
    }

    return new SSLConnectionSocketFactory(sslcontextBuilder.build(), new HostnameVerifier() {
        @Override
        public boolean verify(final String s, final SSLSession sslSession) {
            return true;
        }
    });
}
 
Example 6
Source File: SecurityUtils.java    From wildfly-camel-examples with Apache License 2.0 6 votes vote down vote up
public static SSLConnectionSocketFactory createSocketFactory(Path truststoreFile, Path keystoreFile, String password)
        throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, CertificateException,
        IOException, UnrecoverableKeyException {
    final char[] pwd = password.toCharArray();
    SSLContextBuilder sslcontextBuilder = SSLContexts.custom()
            .loadTrustMaterial(truststoreFile.toFile(), pwd, TrustSelfSignedStrategy.INSTANCE)
    ;
    if (keystoreFile != null) {
        sslcontextBuilder.loadKeyMaterial(keystoreFile.toFile(), pwd, pwd);
    }

    sslcontextBuilder.setProtocol("TLSv1.2");

    return new SSLConnectionSocketFactory(sslcontextBuilder.build(), new HostnameVerifier() {
        @Override
        public boolean verify(final String s, final SSLSession sslSession) {
            return true;
        }
    });
}
 
Example 7
Source File: RestClient.java    From ats-framework with Apache License 2.0 5 votes vote down vote up
private Registry constructRegistry() {

        try {
            SSLContextBuilder builder = SSLContextBuilder.create();

            builder.useProtocol(this.supportedProtocols[0]);

            if (!StringUtils.isNullOrEmpty(clientConfigurator.getCertificateFileName())) {
                builder.loadKeyMaterial(SslUtils.loadKeystore(clientConfigurator.getCertificateFileName(),
                                                              clientConfigurator.getCertificateFilePassword()),
                                        clientConfigurator.getCertificateFilePassword().toCharArray());
            }

            // Trust all certificates
            builder.loadTrustMaterial(new TrustStrategy() {
                @Override
                public boolean isTrusted( X509Certificate[] chain, String authType ) throws CertificateException {

                    return true;
                }
            });
            SSLContext sslContext = builder.build();

            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                                                                              new NoopHostnameVerifier());

            Registry registry = RegistryBuilder.create().register("https", sslsf).build();

            return registry;
        } catch (Exception e) {
            throw new RuntimeException("Unable to setup SSL context for REST client with Apache connector provider", e);
        }
    }
 
Example 8
Source File: CommonsDataLoader.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
private RegistryBuilder<ConnectionSocketFactory> setConnectionManagerSchemeHttps(
		final RegistryBuilder<ConnectionSocketFactory> socketFactoryRegistryBuilder) {
	try {

		SSLContextBuilder sslContextBuilder = SSLContextBuilder.create();
		sslContextBuilder.setProtocol(sslProtocol);
		
		TrustStrategy trustStrategy = getTrustStrategy();
		if (trustStrategy != null) {
			LOG.debug("Set the TrustStrategy");
			sslContextBuilder.loadTrustMaterial(null, trustStrategy);
		}

		final KeyStore sslTrustStore = getSSLTrustStore();
		if (sslTrustStore != null) {
			LOG.debug("Set the SSL trust store as trust materials");
			sslContextBuilder.loadTrustMaterial(sslTrustStore, trustStrategy);
		}

		final KeyStore sslKeystore = getSSLKeyStore();
		if (sslKeystore != null) {
			LOG.debug("Set the SSL keystore as key materials");
			final char[] password = sslKeystorePassword != null ? sslKeystorePassword.toCharArray() : null;
			sslContextBuilder.loadKeyMaterial(sslKeystore, password);
			if (loadKeyStoreAsTrustMaterial) {
				LOG.debug("Set the SSL keystore as trust materials");
				sslContextBuilder.loadTrustMaterial(sslKeystore, trustStrategy);
			}
		}

		SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContextBuilder.build(), getSupportedSSLProtocols(),
				getSupportedSSLCipherSuites(), getHostnameVerifier());
		return socketFactoryRegistryBuilder.register("https", sslConnectionSocketFactory);
	} catch (final Exception e) {
		throw new DSSException("Unable to configure the SSLContext/SSLConnectionSocketFactory", e);
	}
}
 
Example 9
Source File: BasicHttpsSecurityApplicationTests.java    From building-microservices with Apache License 2.0 5 votes vote down vote up
private SSLConnectionSocketFactory socketFactory() throws Exception {
	char[] password = "password".toCharArray();
	KeyStore truststore = KeyStore.getInstance("PKCS12");
	truststore.load(new ClassPathResource("rod.p12").getInputStream(), password);
	SSLContextBuilder builder = new SSLContextBuilder();
	builder.loadKeyMaterial(truststore, password);
	builder.loadTrustMaterial(truststore, new TrustSelfSignedStrategy());
	return new SSLConnectionSocketFactory(builder.build(),
			new NoopHostnameVerifier());
}
 
Example 10
Source File: X509ApplicationTests.java    From building-microservices with Apache License 2.0 5 votes vote down vote up
private SSLConnectionSocketFactory socketFactory() throws Exception {
    char[] password = "password".toCharArray();
    KeyStore truststore = KeyStore.getInstance("PKCS12");
    truststore.load(new ClassPathResource("rod.p12").getInputStream(), password);
    SSLContextBuilder builder = new SSLContextBuilder();
    builder.loadKeyMaterial(truststore, password);
    builder.loadTrustMaterial(truststore, new TrustSelfSignedStrategy());
    return new SSLConnectionSocketFactory(builder.build(),
            new NoopHostnameVerifier());
}
 
Example 11
Source File: SSLTestConfig.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * Builds a new SSLContext for jetty servers which have been configured based on the settings of 
 * this object.
 *
 * NOTE: Uses a completely insecure {@link SecureRandom} instance to prevent tests from blocking 
 * due to lack of entropy, also explicitly allows the use of self-signed 
 * certificates (since that's what is almost always used during testing).
 * almost always used during testing). 
 */
public SSLConfig buildServerSSLConfig() {
  if (!isSSLMode()) {
    return null;
  }

  return new SSLConfig(isSSLMode(), isClientAuthMode(), null, null, null, null) {
    @Override
    public SslContextFactory.Server createContextFactory() {
      SslContextFactory.Server factory = new SslContextFactory.Server();
      try {
        SSLContextBuilder builder = SSLContexts.custom();
        builder.setSecureRandom(NotSecurePsuedoRandom.INSTANCE);

        builder.loadKeyMaterial(buildKeyStore(keyStore, TEST_PASSWORD), TEST_PASSWORD.toCharArray());

        if (isClientAuthMode()) {
          builder.loadTrustMaterial(buildKeyStore(trustStore, TEST_PASSWORD), new TrustSelfSignedStrategy()).build();

        }
        factory.setSslContext(builder.build());
      } catch (Exception e) {
        throw new RuntimeException("ssl context init failure: " + e.getMessage(), e);
      }
      factory.setNeedClientAuth(isClientAuthMode());
      return factory;
    }
  };
}
 
Example 12
Source File: GoAgentServerHttpClientBuilder.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Override
public CloseableHttpClient build() throws Exception {
    HttpClientBuilder builder = HttpClients.custom();
    builder.useSystemProperties();
    builder
            .setDefaultSocketConfig(SocketConfig.custom()
                    .setTcpNoDelay(true)
                    .setSoKeepAlive(true)
                    .build()
            )
            .setKeepAliveStrategy(DefaultConnectionKeepAliveStrategy.INSTANCE);

    HostnameVerifier hostnameVerifier = sslVerificationMode.verifier();
    TrustStrategy trustStrategy = sslVerificationMode.trustStrategy();
    KeyStore trustStore = agentTruststore();

    SSLContextBuilder sslContextBuilder = SSLContextBuilder.create();

    if (trustStore != null || trustStrategy != null) {
        sslContextBuilder.loadTrustMaterial(trustStore, trustStrategy);
    }

    KeyStore keystore = agentKeystore();

    if (keystore != null) {
        sslContextBuilder.loadKeyMaterial(keystore, agentKeystorePassword);
    }

    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContextBuilder.build(), hostnameVerifier);
    builder.setSSLSocketFactory(sslConnectionSocketFactory);
    return builder.build();
}
 
Example 13
Source File: YouTrackClient.java    From vk-java-sdk with MIT License 5 votes vote down vote up
private SSLConnectionSocketFactory initSslContext(String keyStoreType, String keyStorePath, String keyStorePassword, String keyPassword,
                                                  String trustStoreType, String trustStorePath, String trustStorePassword)
        throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException, UnrecoverableKeyException, KeyManagementException {

    SSLContextBuilder sslContextBuilder = SSLContexts.custom();

    if (StringUtils.isNoneBlank(keyStorePath)) {
        KeyStore keyStore = SslUtils.getStore(keyStoreType, keyStorePath, keyStorePassword);
        if (keyStore.size() == 0) {
            throw new IllegalStateException("Key store has no keys");
        }

        sslContextBuilder.loadKeyMaterial(keyStore, keyPassword.toCharArray());
    }

    if (StringUtils.isNoneBlank(trustStorePath)) {
        KeyStore trustStore = SslUtils.getStore(trustStoreType, trustStorePath, trustStorePassword);
        if (trustStore.size() == 0) {
            throw new IllegalStateException("Trust store has no keys");
        }

        sslContextBuilder.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy());
    }

    return new SSLConnectionSocketFactory(
            sslContextBuilder.build(),
            SSLConnectionSocketFactory.getDefaultHostnameVerifier());
}
 
Example 14
Source File: HttpsFactory.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
private void loadKeyringMaterial(SSLContextBuilder sslContextBuilder) throws UnrecoverableKeyException,
        NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException {
    log.info("Loading trust key ring: " + config.getKeyStore());
    sslContextBuilder.loadKeyMaterial(keyRingUrl(config.getKeyStore()),
            config.getKeyStorePassword() == null ? null : config.getKeyStorePassword().toCharArray(),
            config.getKeyPassword() == null ? null : config.getKeyPassword().toCharArray(), null);
}
 
Example 15
Source File: SSLTruststoreUtil.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static HttpClient getHttpClientWithSSL(File keyStoreFile, String keyStorePassword, String keyStoreProvider,
        File trustStoreFile, String trustStorePassword, String trustStoreProvider) {

    try {
        KeyStore trustStore = KeyStore.getInstance(trustStoreProvider);
        try (FileInputStream fis = new FileInputStream(trustStoreFile)) {
            trustStore.load(fis, trustStorePassword.toCharArray());
        }
        SSLContextBuilder sslContextBuilder = SSLContexts.custom()
                .setProtocol("TLS")
                .loadTrustMaterial(trustStore, null);
        if (keyStoreFile != null) {
            KeyStore keyStore = KeyStore.getInstance(keyStoreProvider);
            try (FileInputStream fis = new FileInputStream(keyStoreFile)) {
                keyStore.load(fis, keyStorePassword.toCharArray());
            }
            sslContextBuilder.loadKeyMaterial(keyStore, keyStorePassword.toCharArray(), null);
        }
        SSLContext sslContext = sslContextBuilder.build();
        SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);

        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", socketFactory)
                .build();

        return HttpClientBuilder.create()
                .setSSLSocketFactory(socketFactory)
                        //.setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
                .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                .setConnectionManager(new PoolingHttpClientConnectionManager(registry))
                .setSchemePortResolver(new DefaultSchemePortResolver())
                .build();

    } catch (Exception e) {
        LOGGER.error("Creating HttpClient with customized SSL failed. We are returning the default one instead.", e);
        return HttpClients.createDefault();
    }
}
 
Example 16
Source File: AvaticaCommonsHttpClientImpl.java    From calcite-avatica with Apache License 2.0 4 votes vote down vote up
protected void loadKeyStore(SSLContextBuilder sslContextBuilder) throws Exception {
  sslContextBuilder.loadKeyMaterial(keystore,
          keystorePassword.toCharArray(), keyPassword.toCharArray());
}
 
Example 17
Source File: HttpClient.java    From deprecated-security-advanced-modules with Apache License 2.0 4 votes vote down vote up
private final HttpAsyncClientBuilder asyncClientBuilder(HttpAsyncClientBuilder httpClientBuilder)
        throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, KeyManagementException {

    // basic auth
    // pki auth

    if (ssl) {

        final SSLContextBuilder sslContextBuilder = SSLContexts.custom();

        if (log.isTraceEnabled()) {
            log.trace("Configure HTTP client with SSL");
        }

        if (trustStore != null) {
            sslContextBuilder.loadTrustMaterial(trustStore, null);
        }

        if (keystore != null) {
            sslContextBuilder.loadKeyMaterial(keystore, keyPassword, new PrivateKeyStrategy() {

                @Override
                public String chooseAlias(Map<String, PrivateKeyDetails> aliases, Socket socket) {
                    if(aliases == null || aliases.isEmpty()) {
                        return keystoreAlias;
                    }

                    if(keystoreAlias == null || keystoreAlias.isEmpty()) {
                        return aliases.keySet().iterator().next();
                    }

                    return keystoreAlias;                    }
            });
        }

        final HostnameVerifier hnv = verifyHostnames?new DefaultHostnameVerifier():NoopHostnameVerifier.INSTANCE;

        final SSLContext sslContext = sslContextBuilder.build();
        httpClientBuilder.setSSLStrategy(new SSLIOSessionStrategy(
                sslContext,
                supportedProtocols,
                supportedCipherSuites,
                hnv
                ));
    }

    if (basicCredentials != null) {
        httpClientBuilder.setDefaultHeaders(Lists.newArrayList(new BasicHeader(HttpHeaders.AUTHORIZATION, "Basic " + basicCredentials)));
    }

    // TODO: set a timeout until we have a proper way to deal with back pressure
    int timeout = 5;

    RequestConfig config = RequestConfig.custom()
      .setConnectTimeout(timeout * 1000)
      .setConnectionRequestTimeout(timeout * 1000)
      .setSocketTimeout(timeout * 1000).build();

    httpClientBuilder.setDefaultRequestConfig(config);

    return httpClientBuilder;

}
 
Example 18
Source File: SettingsBasedSSLConfiguratorTest.java    From deprecated-security-advanced-modules with Apache License 2.0 4 votes vote down vote up
private SSLContext createSSLContext(String trustStorePath, String keyStorePath, String password) {

            try {
                TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
                KeyStore trustStore = KeyStore.getInstance("JKS");
                InputStream trustStream = new FileInputStream(
                        FileHelper.getAbsoluteFilePathFromClassPath(trustStorePath).toFile());
                trustStore.load(trustStream, password.toCharArray());
                tmf.init(trustStore);

                KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
                KeyStore keyStore = KeyStore.getInstance("JKS");

                Path path = FileHelper.getAbsoluteFilePathFromClassPath(keyStorePath);

                if (path == null) {
                    throw new RuntimeException("Could not find " + keyStorePath);
                }

                InputStream keyStream = new FileInputStream(path.toFile());

                keyStore.load(keyStream, password.toCharArray());
                kmf.init(keyStore, password.toCharArray());

                SSLContextBuilder sslContextBuilder = SSLContexts.custom();

                sslContextBuilder.loadTrustMaterial(trustStore, null);

                sslContextBuilder.loadKeyMaterial(keyStore, password.toCharArray(), new PrivateKeyStrategy() {

                    @Override
                    public String chooseAlias(Map<String, PrivateKeyDetails> aliases, Socket socket) {
                        return "node1";
                    }
                });

                return sslContextBuilder.build();
            } catch (GeneralSecurityException | IOException e) {
                throw new RuntimeException(e);
            }
        }
 
Example 19
Source File: KeySetRetrieverTest.java    From deprecated-security-advanced-modules with Apache License 2.0 4 votes vote down vote up
@Test
public void clientCertTest() throws Exception {

    try (MockIpdServer sslMockIdpServer = new MockIpdServer(TestJwk.Jwks.ALL, SocketUtils.findAvailableTcpPort(),
            true) {
        @Override
        protected void handleDiscoverRequest(HttpRequest request, HttpResponse response, HttpContext context)
                throws HttpException, IOException {

            MockIpdServer.SSLTestHttpServerConnection connection = (MockIpdServer.SSLTestHttpServerConnection) ((HttpCoreContext) context)
                    .getConnection();

            X509Certificate peerCert = (X509Certificate) connection.getPeerCertificates()[0];

            try {
                String sha256Fingerprint = Hashing.sha256().hashBytes(peerCert.getEncoded()).toString();

                Assert.assertEquals("04b2b8baea7a0a893f0223d95b72081e9a1e154a0f9b1b4e75998085972b1b68",
                        sha256Fingerprint);

            } catch (CertificateEncodingException e) {
                throw new RuntimeException(e);
            }

            super.handleDiscoverRequest(request, response, context);
        }
    }) {
        SSLContextBuilder sslContextBuilder = SSLContexts.custom();

        KeyStore trustStore = KeyStore.getInstance("JKS");
        InputStream trustStream = new FileInputStream(
                FileHelper.getAbsoluteFilePathFromClassPath("jwt/truststore.jks").toFile());
        trustStore.load(trustStream, "changeit".toCharArray());

        KeyStore keyStore = KeyStore.getInstance("JKS");
        InputStream keyStream = new FileInputStream(
                FileHelper.getAbsoluteFilePathFromClassPath("jwt/spock-keystore.jks").toFile());

        keyStore.load(keyStream, "changeit".toCharArray());

        sslContextBuilder.loadTrustMaterial(trustStore, null);

        sslContextBuilder.loadKeyMaterial(keyStore, "changeit".toCharArray(), new PrivateKeyStrategy() {

            @Override
            public String chooseAlias(Map<String, PrivateKeyDetails> aliases, Socket socket) {
                return "spock";
            }
        });

        SettingsBasedSSLConfigurator.SSLConfig sslConfig = new SettingsBasedSSLConfigurator.SSLConfig(
                sslContextBuilder.build(), new String[] { "TLSv1.2", "TLSv1.1" }, null, null, false, false, false,
                trustStore, null, keyStore, null, null);

        KeySetRetriever keySetRetriever = new KeySetRetriever(sslMockIdpServer.getDiscoverUri(), sslConfig, false);

        keySetRetriever.get();

    }
}
 
Example 20
Source File: AbstractUnitTest.java    From deprecated-security-ssl with Apache License 2.0 2 votes vote down vote up
protected final CloseableHttpClient getHTTPClient() throws Exception {

        final HttpClientBuilder hcb = HttpClients.custom();

        if (enableHTTPClientSSL) {

            log.debug("Configure HTTP client with SSL");

            final KeyStore myTrustStore = KeyStore.getInstance("JKS");
            myTrustStore.load(new FileInputStream(getAbsoluteFilePathFromClassPath("truststore.jks").toFile()), "changeit".toCharArray());

            final KeyStore keyStore = KeyStore.getInstance(keystore.toLowerCase().endsWith("p12")?"PKCS12":"JKS");
            keyStore.load(new FileInputStream(getAbsoluteFilePathFromClassPath(keystore).toFile()), "changeit".toCharArray());

            final SSLContextBuilder sslContextbBuilder = SSLContexts.custom().useProtocol("TLS");

            if (trustHTTPServerCertificate) {
                sslContextbBuilder.loadTrustMaterial(myTrustStore, null);
            }

            if (sendHTTPClientCertificate) {
                sslContextbBuilder.loadKeyMaterial(keyStore, "changeit".toCharArray());
            }
            
            final SSLContext sslContext = sslContextbBuilder.build();

            String[] protocols = null;

            if (enableHTTPClientSSLv3Only) {
                protocols = new String[] { "SSLv3" };
            } else {
                protocols = new String[] { "TLSv1", "TLSv1.1", "TLSv1.2" };
            }
            
            final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, protocols, null, NoopHostnameVerifier.INSTANCE);

            hcb.setSSLSocketFactory(sslsf);
        }

        hcb.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(60 * 1000).build());

        return hcb.build();
    }