Java Code Examples for javax.net.ssl.SSLContext#getInstance()

The following examples show how to use javax.net.ssl.SSLContext#getInstance() . These examples are extracted from open source projects. 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
public static void initiate() {
	// if (initiated) return;
	SSLContext sc;
	try {
		TrustManager[] trustAllCerts = new TrustManager[] { new EclipseSWTTrustManager() };
		sc = SSLContext.getInstance("SSL");
		sc.init(null, trustAllCerts, new java.security.SecureRandom());
		HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
		HostnameVerifier allHostsValid = new HostnameVerifier() {
			public boolean verify(String hostname, SSLSession session) {
				return true;
			}
		};
		HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
	} catch (Exception e) {
		log.error(e.getMessage(),e);
	}
	initiated = true;
}
 
Example 2
Source Project: openAGV   File: SecureSslContextFactory.java    License: 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 3
protected final OkHttpClient getHttpClient() throws Exception {
    File ksFile = new File(keyStore);
    KeyStore trusted = KeyStore.getInstance("JKS");
    FileInputStream in = new FileInputStream(ksFile);
    trusted.load(in, password.toCharArray());
    in.close();
    SSLContext sslContext = SSLContext.getInstance("TLS");
    TrustManagerFactory trustManagerFactory = InsecureTrustManagerFactory.INSTANCE;
    X509TrustManager trustManager = (X509TrustManager) trustManagerFactory.getTrustManagers()[0];
    sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
    OkHttpClient client = new okhttp3.OkHttpClient.Builder()
            .sslSocketFactory(sslContext.getSocketFactory(), trustManager)
            .readTimeout(1, TimeUnit.MINUTES)
            .writeTimeout(1, TimeUnit.MINUTES)
            .build();
    return client;
}
 
Example 4
Source Project: datakernel   File: AsyncHttpClientTest.java    License: Apache License 2.0 6 votes vote down vote up
private static SSLContext createSslContext() {
	try {
		SSLContext instance = SSLContext.getInstance("TLSv1.2");

		KeyStore keyStore = KeyStore.getInstance("JKS");
		KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
		try (InputStream input = new FileInputStream(new File(KEYSTORE_PATH))) {
			keyStore.load(input, KEYSTORE_PASS.toCharArray());
		}
		kmf.init(keyStore, KEY_PASS.toCharArray());

		KeyStore trustStore = KeyStore.getInstance("JKS");
		TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
		try (InputStream input = new FileInputStream(new File(TRUSTSTORE_PATH))) {
			trustStore.load(input, TRUSTSTORE_PASS.toCharArray());
		}
		tmf.init(trustStore);

		instance.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());
		return instance;
	} catch (Exception e) {
		throw new AssertionError(e);
	}
}
 
Example 5
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 6
@Nonnull
@Override
protected SSLContext compute() {
  String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
  if (algorithm == null) {
    algorithm = "SunX509";
  }

  try {
    KeyStore ks = KeyStore.getInstance("JKS");
    char[] password = "jetbrains".toCharArray();
    //noinspection IOResourceOpenedButNotSafelyClosed
    ks.load(getClass().getResourceAsStream("cert.jks"), password);
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
    kmf.init(ks, password);
    SSLContext serverContext = SSLContext.getInstance("TLS");
    serverContext.init(kmf.getKeyManagers(), null, null);
    return serverContext;
  }
  catch (Exception e) {
    throw new RuntimeException(e);
  }
}
 
Example 7
Source Project: MyBox   File: NetworkTools.java    License: Apache License 2.0 6 votes vote down vote up
public static File httpsPage(String address) {
    try {
        URL url = new URL(address);
        File pageFile = FileTools.getTempFile(".htm");
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        SSLContext sc = SSLContext.getInstance(CommonValues.HttpsProtocal);
        sc.init(null, trustAllManager(), new SecureRandom());
        connection.setSSLSocketFactory(sc.getSocketFactory());
        connection.setHostnameVerifier(trustAllVerifier());
        connection.connect();
        try ( BufferedInputStream inStream = new BufferedInputStream(connection.getInputStream());
                 BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(pageFile))) {
            byte[] buf = new byte[CommonValues.IOBufferLength];
            int len;
            while ((len = inStream.read(buf)) != -1) {
                outputStream.write(buf, 0, len);
            }
        }
        return pageFile;
    } catch (Exception e) {
        logger.error(e.toString());
        return null;
    }
}
 
Example 8
/**
 * Factory method that builds a new SSLConnectionSocketFactory.
 * @param options the current WebClientOptions
 * @return the SSLConnectionSocketFactory
 */
public static SSLConnectionSocketFactory buildSSLSocketFactory(final WebClientOptions options) {
    try {
        final String[] sslClientProtocols = options.getSSLClientProtocols();
        final String[] sslClientCipherSuites = options.getSSLClientCipherSuites();

        final boolean useInsecureSSL = options.isUseInsecureSSL();

        if (!useInsecureSSL) {
            final KeyStore keyStore = options.getSSLClientCertificateStore();
            final KeyStore trustStore = options.getSSLTrustStore();

            return new HtmlUnitSSLConnectionSocketFactory(keyStore,
                    keyStore == null ? null : options.getSSLClientCertificatePassword(),
                    trustStore, useInsecureSSL,
                    sslClientProtocols, sslClientCipherSuites);
        }

        // we need insecure SSL + SOCKS awareness
        String protocol = options.getSSLInsecureProtocol();
        if (protocol == null) {
            protocol = "SSL";
        }
        final SSLContext sslContext = SSLContext.getInstance(protocol);
        sslContext.init(getKeyManagers(options), new TrustManager[]{new InsecureTrustManager2()}, null);

        final SSLConnectionSocketFactory factory = new HtmlUnitSSLConnectionSocketFactory(sslContext,
            NoopHostnameVerifier.INSTANCE,
            useInsecureSSL, sslClientProtocols, sslClientCipherSuites);
        return factory;
    }
    catch (final GeneralSecurityException e) {
        throw new RuntimeException(e);
    }
}
 
Example 9
private void setHttpClientProperties() throws CelleryCellSTSException {

        CelleryTrustManager celleryTrustManager = new CelleryTrustManager();
        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, new TrustManager[]{celleryTrustManager}, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
            HttpsURLConnection.setDefaultHostnameVerifier(
                    new CelleryHostnameVerifier(new DefaultHostnameVerifier()));
        } catch (KeyManagementException | NoSuchAlgorithmException e) {
            throw new CelleryCellSTSException("Error while initializing SSL context");
        }

    }
 
Example 10
Source Project: quill   File: UnsafeHttpClientFactory.java    License: MIT License 5 votes vote down vote up
private SSLSocketFactory getUnsafeSslSocketFactory() {
    try {
        // Create a trust manager that does not validate certificate chains
        final TrustManager[] trustAllCerts = new TrustManager[] { mGullibleTrustManager };
        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        // Create an ssl socket factory with our all-trusting manager
        return sslContext.getSocketFactory();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 11
/**
 * Creates a new instance.
 * @param trustCertChainFile an X.509 certificate chain file in PEM format.
 *                      {@code null} to use the system default
 * @param trustManagerFactory the {@link TrustManagerFactory} that provides the {@link TrustManager}s
 *                            that verifies the certificates sent from servers.
 *                            {@code null} to use the default or the results of parsing {@code trustCertChainFile}
 * @param keyCertChainFile an X.509 certificate chain file in PEM format.
 *                      This provides the public key for mutual authentication.
 *                      {@code null} to use the system default
 * @param keyFile a PKCS#8 private key file in PEM format.
 *                      This provides the private key for mutual authentication.
 *                      {@code null} for no mutual authentication.
 * @param keyPassword the password of the {@code keyFile}.
 *                    {@code null} if it's not password-protected.
 *                    Ignored if {@code keyFile} is {@code null}.
 * @param keyManagerFactory the {@link KeyManagerFactory} that provides the {@link KeyManager}s
 *                          that is used to encrypt data being sent to servers.
 *                          {@code null} to use the default or the results of parsing
 *                          {@code keyCertChainFile} and {@code keyFile}.
 * @param ciphers the cipher suites to enable, in the order of preference.
 *                {@code null} to use the default cipher suites.
 * @param cipherFilter a filter to apply over the supplied list of ciphers
 * @param apn Application Protocol Negotiator object.
 * @param sessionCacheSize the size of the cache used for storing SSL session objects.
 *                         {@code 0} to use the default value.
 * @param sessionTimeout the timeout for the cached SSL session objects, in seconds.
 *                       {@code 0} to use the default value.
 */
public JdkSslClientContext(File trustCertChainFile, TrustManagerFactory trustManagerFactory,
        File keyCertChainFile, File keyFile, String keyPassword, KeyManagerFactory keyManagerFactory,
        Iterable<String> ciphers, CipherSuiteFilter cipherFilter, JdkApplicationProtocolNegotiator apn,
        long sessionCacheSize, long sessionTimeout) throws SSLException {
    super(ciphers, cipherFilter, apn);

    try {
        if (trustCertChainFile != null) {
            trustManagerFactory = buildTrustManagerFactory(trustCertChainFile, trustManagerFactory);
        }
        if (keyFile != null) {
            keyManagerFactory = buildKeyManagerFactory(keyCertChainFile, keyFile, keyPassword, keyManagerFactory);
        }
        ctx = SSLContext.getInstance(PROTOCOL);
        ctx.init(keyManagerFactory == null ? null : keyManagerFactory.getKeyManagers(),
                 trustManagerFactory == null ? null : trustManagerFactory.getTrustManagers(),
                 null);

        SSLSessionContext sessCtx = ctx.getClientSessionContext();
        if (sessionCacheSize > 0) {
            sessCtx.setSessionCacheSize((int) Math.min(sessionCacheSize, Integer.MAX_VALUE));
        }
        if (sessionTimeout > 0) {
            sessCtx.setSessionTimeout((int) Math.min(sessionTimeout, Integer.MAX_VALUE));
        }
    } catch (Exception e) {
        throw new SSLException("failed to initialize the client-side SSL context", e);
    }
}
 
Example 12
public DummySSLSocketFactory() {
	try {
		SSLContext sslcontext = SSLContext.getInstance("TLS");
		sslcontext.init(null, new TrustManager[] { new EclipseSWTTrustManager() }, null);
		factory = (SSLSocketFactory) sslcontext.getSocketFactory();
	} catch (Exception ex) {
		log.error(ex.getMessage(), ex);
	}
}
 
Example 13
Source Project: onenet-iot-project   File: SslUtil.java    License: MIT License 5 votes vote down vote up
public static SSLSocketFactory getSocketFactory(final InputStream caCrtFile) throws NoSuchAlgorithmException,
        IOException, KeyStoreException, CertificateException, KeyManagementException {
    Security.addProvider(new BouncyCastleProvider());

    //===========加载 ca 证书==================================
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    if (null != caCrtFile) {
        // 加载本地指定的 ca 证书
        PEMReader reader = new PEMReader(new InputStreamReader(caCrtFile));
        X509Certificate caCert = (X509Certificate) reader.readObject();
        reader.close();

        // CA certificate is used to authenticate server
        KeyStore caKs = KeyStore.getInstance(KeyStore.getDefaultType());
        caKs.load(null, null);
        caKs.setCertificateEntry("ca-certificate", caCert);
        // 把ca作为信任的 ca 列表,来验证服务器证书
        tmf.init(caKs);
    } else {
        //使用系统默认的安全证书
        tmf.init((KeyStore) null);
    }

    // ============finally, create SSL socket factory==============
    SSLContext context = SSLContext.getInstance("TLSv1.2");
    context.init(null, tmf.getTrustManagers(), null);

    return context.getSocketFactory();
}
 
Example 14
private SslHandler initSslHandler(Properties props) {
  final String jksPath = props.getProperty(Constants.JKS_PATH_PROPERTY_NAME);
  LOG.info("Starting SSL using keystore at {}", jksPath);
  if (jksPath == null || jksPath.isEmpty()) {
    //key_store_password or key_manager_password are empty
    LOG.warn("You have configured the SSL port but not the jks_path, SSL not started");
    return null;
  }

  //if we have the port also the jks then keyStorePassword and keyManagerPassword
  //has to be defined
  final String keyStorePassword = props.getProperty(
      Constants.KEY_STORE_PASSWORD_PROPERTY_NAME);
  final String keyManagerPassword = props.getProperty(
      Constants.KEY_MANAGER_PASSWORD_PROPERTY_NAME);
  if (keyStorePassword == null || keyStorePassword.isEmpty()) {
    //key_store_password or key_manager_password are empty
    LOG.warn("You have configured the SSL port but not the key_store_password, SSL not started");
    return null;
  }
  if (keyManagerPassword == null || keyManagerPassword.isEmpty()) {
    //key_manager_password or key_manager_password are empty
    LOG.warn("You have configured the SSL port but not the"
        + " key_manager_password, SSL not started");
    return null;
  }

  try {
    InputStream jksInputStream = jksDatastore(jksPath);
    SSLContext serverContext = SSLContext.getInstance("TLS");
    final KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(jksInputStream, keyStorePassword.toCharArray());
    final KeyManagerFactory kmf = KeyManagerFactory.getInstance(
        KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(ks, keyManagerPassword.toCharArray());
    serverContext.init(kmf.getKeyManagers(), null, null);

    SSLEngine engine = serverContext.createSSLEngine();
    engine.setUseClientMode(false);
    return new SslHandler(engine);
  } catch (NoSuchAlgorithmException | UnrecoverableKeyException
      | CertificateException | KeyStoreException
      | KeyManagementException | IOException ex) {
    LOG.error("Can't start SSL layer!", ex);
    return null;
  }
}
 
Example 15
/** 
 * Generate a socket factory with this trust manager. Derby
 * Utility routine which is not part of the X509TrustManager
 * interface.
 **/
public static SocketFactory getSocketFactory()
    throws java.security.NoSuchAlgorithmException,
           java.security.KeyManagementException,
           java.security.NoSuchProviderException,
           java.security.KeyStoreException,
           java.security.UnrecoverableKeyException,
           java.security.cert.CertificateException,
           java.io.IOException
{
    if (thisManager == null) {
        thisManager = new TrustManager [] {new NaiveTrustManager()};
    }

    SSLContext ctx = SSLContext.getInstance("SSL");
    
    if (ctx.getProvider().getName().equals("SunJSSE") &&
        (System.getProperty("javax.net.ssl.keyStore") != null) &&
        (System.getProperty("javax.net.ssl.keyStorePassword") != null)) {
        
        // SunJSSE does not give you a working default keystore
        // when using your own trust manager. Since a keystore is
        // needed on the client when the server does
        // peerAuthentication, we have to provide one working the
        // same way as the default one.

        String keyStore = 
            System.getProperty("javax.net.ssl.keyStore");
        String keyStorePassword =
            System.getProperty("javax.net.ssl.keyStorePassword");
        
        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(new FileInputStream(keyStore),
                keyStorePassword.toCharArray());
        
        KeyManagerFactory kmf = 
            KeyManagerFactory.getInstance("SunX509", "SunJSSE");
        kmf.init(ks, keyStorePassword.toCharArray());

        ctx.init(kmf.getKeyManagers(),
                 thisManager,
                 null); // Use default random source
    } else {
        ctx.init(null, // Use default key manager
                 thisManager,
                 null); // Use default random source
    }

    return ctx.getSocketFactory();
 }
 
Example 16
Source Project: cxf   File: SSLv3Test.java    License: Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testSSLv3ServerNotAllowedByDefault() throws Exception {

    SpringBusFactory bf = new SpringBusFactory();
    URL busFile = SSLv3Test.class.getResource("sslv3-client.xml");

    Bus bus = bf.createBus(busFile.toString());
    BusFactory.setDefaultBus(bus);
    BusFactory.setThreadDefaultBus(bus);

    System.setProperty("https.protocols", "SSLv3");

    URL service = new URL("https://localhost:" + PORT);
    HttpsURLConnection connection = (HttpsURLConnection) service.openConnection();

    connection.setHostnameVerifier(new DisableCNCheckVerifier());

    SSLContext sslContext = SSLContext.getInstance("SSL");

    KeyStore trustedCertStore = KeyStore.getInstance("jks");
    try (InputStream keystore = ClassLoaderUtils.getResourceAsStream("keys/Truststore.jks", SSLv3Test.class)) {
        trustedCertStore.load(keystore, null);
    }

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(trustedCertStore);
    TrustManager[] trustManagers = tmf.getTrustManagers();

    sslContext.init(null, trustManagers, new java.security.SecureRandom());
    connection.setSSLSocketFactory(sslContext.getSocketFactory());

    try {
        connection.connect();
        fail("Failure expected on an SSLv3 connection attempt");
    } catch (IOException ex) {
        // expected
    }

    System.clearProperty("https.protocols");

    bus.shutdown(true);
}
 
Example 17
Source Project: gemfirexd-oss   File: NaiveTrustManager.java    License: Apache License 2.0 4 votes vote down vote up
/** 
 * Generate a socket factory with this trust manager. Derby
 * Utility routine which is not part of the X509TrustManager
 * interface.
 **/
public static SocketFactory getSocketFactory()
    throws java.security.NoSuchAlgorithmException,
           java.security.KeyManagementException,
           java.security.NoSuchProviderException,
           java.security.KeyStoreException,
           java.security.UnrecoverableKeyException,
           java.security.cert.CertificateException,
           java.io.IOException
{
    if (thisManager == null) {
        thisManager = new TrustManager [] {new NaiveTrustManager()};
    }

    SSLContext ctx = SSLContext.getInstance("SSL");
    
    if (ctx.getProvider().getName().equals("SunJSSE") &&
        (PropertyUtil.getSystemProperty("javax.net.ssl.keyStore") != null) &&
        (PropertyUtil.getSystemProperty("javax.net.ssl.keyStorePassword") != null)) {
        
        // SunJSSE does not give you a working default keystore
        // when using your own trust manager. Since a keystore is
        // needed on the client when the server does
        // peerAuthentication, we have to provide one working the
        // same way as the default one.

        String keyStore = 
            PropertyUtil.getSystemProperty("javax.net.ssl.keyStore");
        String keyStorePassword =
            PropertyUtil.getSystemProperty("javax.net.ssl.keyStorePassword");
        
        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(new FileInputStream(keyStore),
                keyStorePassword.toCharArray());
        
        KeyManagerFactory kmf = 
            KeyManagerFactory.getInstance("SunX509", "SunJSSE");
        kmf.init(ks, keyStorePassword.toCharArray());

        ctx.init(kmf.getKeyManagers(),
                 thisManager,
                 null); // Use default random source
    } else {
        ctx.init(null, // Use default key manager
                 thisManager,
                 null); // Use default random source
    }

    return ctx.getSocketFactory();
}
 
Example 18
public static void downLoadFromUrlHttps(String urlStr, String fileName,
        String savePath) throws Exception {
    // 创建SSLContext
    SSLContext sslContext = SSLContext.getInstance("SSL");
    TrustManager[] tm = { new HttpsTrustManager() };
    // 初始化
    sslContext.init(null, tm, new java.security.SecureRandom());
    // 获取SSLSocketFactory对象
    SSLSocketFactory ssf = sslContext.getSocketFactory();
    // url对象
    URL url = new URL(urlStr);
    // 打开连接
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    /**
     * 这一步的原因: 当访问HTTPS的网址。您可能已经安装了服务器证书到您的JRE的keystore
     * 但是服务器的名称与证书实际域名不相等。这通常发生在你使用的是非标准网上签发的证书。
     * 
     * 解决方法:让JRE相信所有的证书和对系统的域名和证书域名。
     * 
     * 如果少了这一步会报错:java.io.IOException: HTTPS hostname wrong: should be <localhost>
     */
    conn.setHostnameVerifier(new HttpsTrustManager().new TrustAnyHostnameVerifier());
    // 设置一些参数
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setUseCaches(false);
    // 设置当前实例使用的SSLSoctetFactory
    conn.setSSLSocketFactory(ssf);
    conn.connect();
 
 
    // 得到输入流
    @Cleanup
    InputStream inputStream = conn.getInputStream();
    byte[] getData = readInputStream(inputStream);
    // 文件保存位置
    File saveDir = new File(savePath);
    if (!saveDir.exists()) {
        saveDir.mkdirs();
    }
    //输出流
    File file = new File(saveDir + File.separator + fileName);
    @Cleanup
    FileOutputStream fos = new FileOutputStream(file);
    fos.write(getData);
}
 
Example 19
Source Project: presto   File: OkHttpUtil.java    License: Apache License 2.0 4 votes vote down vote up
public static void setupSsl(
        OkHttpClient.Builder clientBuilder,
        Optional<String> keyStorePath,
        Optional<String> keyStorePassword,
        Optional<String> trustStorePath,
        Optional<String> trustStorePassword)
{
    if (!keyStorePath.isPresent() && !trustStorePath.isPresent()) {
        return;
    }

    try {
        // load KeyStore if configured and get KeyManagers
        KeyStore keyStore = null;
        KeyManager[] keyManagers = null;
        if (keyStorePath.isPresent()) {
            char[] keyManagerPassword;
            try {
                // attempt to read the key store as a PEM file
                keyStore = PemReader.loadKeyStore(new File(keyStorePath.get()), new File(keyStorePath.get()), keyStorePassword);
                // for PEM encoded keys, the password is used to decrypt the specific key (and does not protect the keystore itself)
                keyManagerPassword = new char[0];
            }
            catch (IOException | GeneralSecurityException ignored) {
                keyManagerPassword = keyStorePassword.map(String::toCharArray).orElse(null);

                keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
                try (InputStream in = new FileInputStream(keyStorePath.get())) {
                    keyStore.load(in, keyManagerPassword);
                }
            }
            validateCertificates(keyStore);
            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyManagerFactory.init(keyStore, keyManagerPassword);
            keyManagers = keyManagerFactory.getKeyManagers();
        }

        // load TrustStore if configured, otherwise use KeyStore
        KeyStore trustStore = keyStore;
        if (trustStorePath.isPresent()) {
            trustStore = loadTrustStore(new File(trustStorePath.get()), trustStorePassword);
        }

        // create TrustManagerFactory
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);

        // get X509TrustManager
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
        if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
            throw new RuntimeException("Unexpected default trust managers:" + Arrays.toString(trustManagers));
        }
        X509TrustManager trustManager = (X509TrustManager) trustManagers[0];

        // create SSLContext
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagers, new TrustManager[] {trustManager}, null);

        clientBuilder.sslSocketFactory(sslContext.getSocketFactory(), trustManager);
    }
    catch (GeneralSecurityException | IOException e) {
        throw new ClientException("Error setting up SSL: " + e.getMessage(), e);
    }
}
 
Example 20
Source Project: PoyntSamples   File: TLSSocketFactory.java    License: MIT License 4 votes vote down vote up
public TLSSocketFactory() throws KeyManagementException, NoSuchAlgorithmException {
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, null, null);
    internalSSLSocketFactory = context.getSocketFactory();
}