Java Code Examples for javax.net.ssl.TrustManagerFactory#init()

The following examples show how to use javax.net.ssl.TrustManagerFactory#init() . 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: SSLCertificateHelper.java    From react-native-tcp-socket with MIT License 6 votes vote down vote up
/**
 * Creates an SSLSocketFactory instance for use with the CA provided in the resource file.
 *
 * @param context        Context used to open up the CA file
 * @param rawResourceUri Raw resource file to the CA (in .crt or .cer format, for instance)
 * @return An SSLSocketFactory which trusts the provided CA when provided to network clients
 */
static SSLSocketFactory createCustomTrustedSocketFactory(@NonNull final Context context, @NonNull final String rawResourceUri) throws IOException, GeneralSecurityException {
    InputStream caInput = getRawResourceStream(context, rawResourceUri);
    // Generate the CA Certificate from the raw resource file
    Certificate ca = CertificateFactory.getInstance("X.509").generateCertificate(caInput);
    caInput.close();
    // Load the key store using the CA
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(null, null);
    keyStore.setCertificateEntry("ca", ca);

    // Initialize the TrustManager with this CA
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(keyStore);

    // Create an SSL context that uses the created trust manager
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, tmf.getTrustManagers(), new SecureRandom());
    return sslContext.getSocketFactory();
}
 
Example 2
Source File: ClientNonSpring.java    From cxf with Apache License 2.0 6 votes vote down vote up
private static void setupTLS(Greeter port)
    throws IOException, GeneralSecurityException {
    final TLSClientParameters tlsCP = new TLSClientParameters();
    tlsCP.setDisableCNCheck(true);

    final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    try (InputStream is = new FileInputStream("src/main/config/clientKeystore.jks")) {
        keyStore.load(is, "cspass".toCharArray());
    }

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(keyStore, "ckpass".toCharArray());
    tlsCP.setKeyManagers(kmf.getKeyManagers());

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(keyStore);
    tlsCP.setTrustManagers(tmf.getTrustManagers());

    ((HTTPConduit) ClientProxy.getClient(port).getConduit()).setTlsClientParameters(tlsCP);
}
 
Example 3
Source File: RootCAProvider.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
@Override
public SSLEngine createSSLEngine(final SSLContext sslContext, final String remoteAddress, final Map<String, X509Certificate> certMap) throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException {
    final KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
    final TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");

    final KeyStore ks = getCaKeyStore();
    kmf.init(ks, getKeyStorePassphrase());
    tmf.init(ks);

    final boolean authStrictness = rootCAAuthStrictness.value();
    final boolean allowExpiredCertificate = rootCAAllowExpiredCert.value();

    TrustManager[] tms = new TrustManager[]{new RootCACustomTrustManager(remoteAddress, authStrictness, allowExpiredCertificate, certMap, caCertificate, crlDao)};
    sslContext.init(kmf.getKeyManagers(), tms, new SecureRandom());
    final SSLEngine sslEngine = sslContext.createSSLEngine();
    sslEngine.setNeedClientAuth(authStrictness);
    return sslEngine;
}
 
Example 4
Source File: ArangoSslTest.java    From arangodb-java-driver-async with Apache License 2.0 6 votes vote down vote up
@Test
@Ignore
public void connect() throws Exception {
	final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
	ks.load(this.getClass().getResourceAsStream(SSL_TRUSTSTORE), SSL_TRUSTSTORE_PASSWORD.toCharArray());

	final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
	kmf.init(ks, SSL_TRUSTSTORE_PASSWORD.toCharArray());

	final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
	tmf.init(ks);

	final SSLContext sc = SSLContext.getInstance("TLS");
	sc.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

	final ArangoDBAsync arangoDB = new ArangoDBAsync.Builder()
			.loadProperties(ArangoSslTest.class.getResourceAsStream("/arangodb-ssl.properties")).useSsl(true)
			.sslContext(sc).build();
	final ArangoDBVersion version = arangoDB.getVersion().get();
	assertThat(version, is(notNullValue()));
}
 
Example 5
Source File: CertUtils.java    From android with MIT License 6 votes vote down vote up
private static TrustManager[] certToTrustManager(String cert) throws GeneralSecurityException {
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    Collection<? extends Certificate> certificates =
            certificateFactory.generateCertificates(Utils.stringToInputStream(cert));
    if (certificates.isEmpty()) {
        throw new IllegalArgumentException("expected non-empty set of trusted certificates");
    }
    KeyStore caKeyStore = newEmptyKeyStore();
    int index = 0;
    for (Certificate certificate : certificates) {
        String certificateAlias = "ca" + Integer.toString(index++);
        caKeyStore.setCertificateEntry(certificateAlias, certificate);
    }
    TrustManagerFactory trustManagerFactory =
            TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(caKeyStore);
    return trustManagerFactory.getTrustManagers();
}
 
Example 6
Source File: RetrofitManager.java    From QuickDevFramework with Apache License 2.0 6 votes vote down vote up
/**
 * SSL single certificate config for OkHttpClient
 */
public static void configSingleTrust(OkHttpClient.Builder builder) {
    try {
        //this file do not exist, replace with your certificate file when you use this method
        KeyStore keyStore = SSLHelper.createKeyStore(new File("test.bks"), "123456");
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
        tmf.init(keyStore);
        TrustManager[] trustManagers = tmf.getTrustManagers();
        SSLContext sslContext = SSLContext.getInstance("SSL");
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustManagers[0]);
        builder.hostnameVerifier((hostname, session) -> true);
    } catch (Exception e) {
        e.printStackTrace();
    }

}
 
Example 7
Source File: SSLUtils.java    From SonarPet with GNU General Public License v3.0 5 votes vote down vote up
@SneakyThrows({NoSuchAlgorithmException.class, KeyStoreException.class})
private static TrustManagerFactory getTrustFactory() {
    TrustManagerFactory factory = TrustManagerFactory.getInstance(
            TrustManagerFactory.getDefaultAlgorithm()
    );
    factory.init((KeyStore) null);
    return factory;
}
 
Example 8
Source File: InsecureHttpsServer.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Starts the server.
 * @throws Exception in case of exception
 */
public void start() throws Exception {
    final URL url = getClass().getClassLoader().getResource("insecureSSL.keystore");
    final KeyStore keystore = KeyStore.getInstance("jks");
    final char[] pwd = "nopassword".toCharArray();
    keystore.load(url.openStream(), pwd);

    final TrustManagerFactory trustManagerFactory = createTrustManagerFactory();
    trustManagerFactory.init(keystore);
    final TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();

    final KeyManagerFactory keyManagerFactory = createKeyManagerFactory();
    keyManagerFactory.init(keystore, pwd);
    final KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();

    final SSLContext serverSSLContext = SSLContext.getInstance("TLS");
    serverSSLContext.init(keyManagers, trustManagers, null);

    localServer_ = new LocalTestServer(serverSSLContext);

    if (html_ != null) {
        final HttpRequestHandler handler = new HttpRequestHandler() {
            @Override
            public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context)
                throws HttpException, IOException {
                response.setEntity(new StringEntity(html_, ContentType.TEXT_HTML));
            }
        };
        localServer_.register("*", handler);
    }
    localServer_.start();
}
 
Example 9
Source File: JKSCertInfo.java    From log4j2-elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public void applyTo(HttpClientFactory.Builder httpClientFactoryBuilder) {

    try (
            FileInputStream keystoreFile = new FileInputStream(new File(keystorePath));
            FileInputStream truststoreFile = new FileInputStream(new File(truststorePath))
    ) {
        KeyStore keyStore = KeyStore.getInstance("jks");
        keyStore.load(keystoreFile, keystorePassword.toCharArray());
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, keystorePassword.toCharArray());

        KeyStore trustStore = KeyStore.getInstance("jks");
        trustStore.load(truststoreFile, truststorePassword.toCharArray());

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

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

        // TODO: add support for hostname verification modes
        httpClientFactoryBuilder.withSslSocketFactory(new SSLConnectionSocketFactory(sslContext));
        httpClientFactoryBuilder.withHttpsIOSessionStrategy(new SSLIOSessionStrategy(sslContext, new NoopHostnameVerifier()));

    } catch (IOException | GeneralSecurityException e) {
        throw new ConfigurationException(configExceptionMessage, e);
    }
}
 
Example 10
Source File: ClientAuthTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testSSLConnectionUsingJavaAPIs() throws Exception {
    URL service = new URL("https://localhost:" + PORT);
    HttpsURLConnection connection = (HttpsURLConnection) service.openConnection();

    connection.setHostnameVerifier(new DisableCNCheckVerifier());

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

    KeyStore ts = KeyStore.getInstance("JKS");
    try (InputStream trustStore =
        ClassLoaderUtils.getResourceAsStream("keys/Truststore.jks", ClientAuthTest.class)) {
        ts.load(trustStore, "password".toCharArray());
    }

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

    KeyStore ks = KeyStore.getInstance("JKS");
    try (InputStream keyStore =
        ClassLoaderUtils.getResourceAsStream("keys/Morpit.jks", ClientAuthTest.class)) {
        ks.load(keyStore, "password".toCharArray());
    }

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(ks, "password".toCharArray());

    sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new java.security.SecureRandom());

    connection.setSSLSocketFactory(sslContext.getSocketFactory());

    connection.connect();

    connection.disconnect();
}
 
Example 11
Source File: ApiUtils.java    From razorpay-java with MIT License 5 votes vote down vote up
private static X509TrustManager createDefaultTrustManager() throws NoSuchAlgorithmException, KeyStoreException {
  TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
  trustManagerFactory.init((KeyStore) null);
  TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
  if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
    throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers));
  }
  X509TrustManager trustManager = (X509TrustManager) trustManagers[0];
  return trustManager;
}
 
Example 12
Source File: OvirtSimpleClientHttpRequestFactory.java    From moVirt with Apache License 2.0 5 votes vote down vote up
private void trustImportedCert(Cert[] certChain) {
    try {
        String keyStoreType = KeyStore.getDefaultType();
        KeyStore keyStore = KeyStore.getInstance(keyStoreType);
        keyStore.load(null, null);
        // try to add certificate - if adding fails do not trust anything
        Cert cert = (certChain.length == 0) ? null : certChain[certChain.length - 1];
        if (cert != null) {
            Certificate certificate = cert.asCertificate();
            if (CertHelper.isCA(certificate)) {
                keyStore.setCertificateEntry("ca_" + propertiesManager.getManagedAccount().getId(), certificate);
            }
        }

        // Create a TrustManager that trusts the CAs in our KeyStore
        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init(keyStore);

        // Create an SSLContext that uses our TrustManager
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, tmf.getTrustManagers(), new java.security.SecureRandom());
        sslSocketFactory = context.getSocketFactory();
    } catch (Exception e) {
        messageHelper.showError(ErrorType.NORMAL, e,
                "Error installing custom certificates - trusting system certificates!");
        try {
            propertiesManager.setCertHandlingStrategy(CertHandlingStrategy.TRUST_SYSTEM);
        } catch (AccountDeletedException ignored) {
        }
    }
}
 
Example 13
Source File: SslExample.java    From arangodb-java-driver with Apache License 2.0 5 votes vote down vote up
@Test
@Ignore
public void connect() throws Exception {
	final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
	ks.load(this.getClass().getResourceAsStream(SSL_TRUSTSTORE), SSL_TRUSTSTORE_PASSWORD.toCharArray());

	final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
	kmf.init(ks, SSL_TRUSTSTORE_PASSWORD.toCharArray());

	final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
	tmf.init(ks);

	final SSLContext sc = SSLContext.getInstance("TLS");
	sc.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);


	final ArangoDB arangoDB = new ArangoDB.Builder()
			.host("127.0.0.1", 8529)
			.password("test")
			.useSsl(true)
			.sslContext(sc)
			.useProtocol(Protocol.HTTP_JSON)
			.build();
	final ArangoDBVersion version = arangoDB.getVersion();
	assertThat(version, is(notNullValue()));
	System.out.println(version.getVersion());
}
 
Example 14
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 15
Source File: HttpsUtil.java    From Focus with GNU General Public License v3.0 5 votes vote down vote up
public MyTrustManager(X509TrustManager localTrustManager) throws NoSuchAlgorithmException, KeyStoreException
{
    TrustManagerFactory var4 = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    var4.init((KeyStore) null);
    defaultTrustManager = chooseTrustManager(var4.getTrustManagers());
    this.localTrustManager = localTrustManager;
}
 
Example 16
Source File: TrustStoreConfiguration.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
public TrustManagerFactory initTrustManagerFactory() throws NoSuchAlgorithmException, KeyStoreException {
    final TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(this.trustManagerFactoryAlgorithm);
    tmFactory.init(this.getKeyStore());
    return tmFactory;
}
 
Example 17
Source File: SecurityServiceImpl.java    From gvnix with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Get certificates in the chain of the host server and import them.
 * <p>
 * Tries to get the certificates in the certificates chain of the host
 * server and import them to:
 * <ol>
 * <li>A custom keystore in <code>SRC_MAIN_RESOURCES/gvnix-cacerts</code></li>
 * <li>The JVM cacerts keystore in
 * <code>$JAVA_HOME/jre/lib/security/cacerts</code>. Here we can have a
 * problem if JVM <code>cacerts</code> file is not writable by the user due
 * to file permissions. In this case we throw an exception informing about
 * the error.</li>
 * </ol>
 * </p>
 * <p>
 * With that operation we can try again to get the WSDL.<br/>
 * Also it exports the chain certificates to <code>.cer</code> files in
 * <code>SRC_MAIN_RESOURCES</code>, so the developer can distribute them for
 * its installation in other environments or just in case we reach the
 * problem with the JVM <code>cacerts</code> file permissions.
 * </p>
 * 
 * @see GvNix509TrustManager#saveCertFile(String, X509Certificate,
 *      FileManager, PathResolver)
 * @see <a href=
 *      "http://download.oracle.com/javase/6/docs/technotes/tools/solaris/keytool.html"
 *      >Java SE keytool</a>.
 */
protected Document installCertificates(String loc, String pass)
        throws NoSuchAlgorithmException, KeyStoreException, Exception,
        KeyManagementException, MalformedURLException, IOException,
        UnknownHostException, SocketException, SAXException {

    // Create a SSL context
    SSLContext context = SSLContext.getInstance("TLS");
    TrustManagerFactory tmf = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());

    // Passphrase of the keystore: "changeit" by default
    char[] passArray = (StringUtils.isNotBlank(pass) ? pass.toCharArray()
            : "changeit".toCharArray());

    // Get the project keystore and copy it from JVM if not exists
    File keystore = getProjectKeystore();

    tmf.init(GvNix509TrustManager.loadKeyStore(keystore, passArray));

    X509TrustManager defaultTrustManager = (X509TrustManager) tmf
            .getTrustManagers()[0];
    GvNix509TrustManager tm = new GvNix509TrustManager(defaultTrustManager);
    context.init(null, new TrustManager[] { tm }, null);
    SSLSocketFactory factory = context.getSocketFactory();

    // Open URL location (default 443 port if not defined)
    URL url = new URL(loc);
    String host = url.getHost();
    int port = url.getPort() == -1 ? 443 : url.getPort();
    SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
    socket.setSoTimeout(10000);

    Document doc = null;
    try {

        socket.startHandshake();
        URLConnection connection = url.openConnection();
        if (connection instanceof HttpsURLConnection) {
            ((HttpsURLConnection) connection).setSSLSocketFactory(factory);
        }

        doc = XmlUtils.getDocumentBuilder().parse(
                connection.getInputStream());

        socket.close();

    }
    catch (SSLException ssle) {

        // Get needed certificates for this host
        getCerts(tm, host, keystore, passArray);
        doc = getWsdl(loc, pass);

    }
    catch (IOException ioe) {

        invalidHostCert(passArray, keystore, tm, host);
    }

    Validate.notNull(doc, "No valid document format");
    return doc;
}
 
Example 18
Source File: ConnectorBootstrap.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
private static SslRMIServerSocketFactory createSslRMIServerSocketFactory(
        String sslConfigFileName,
        String[] enabledCipherSuites,
        String[] enabledProtocols,
        boolean sslNeedClientAuth,
        String bindAddress) {
    if (sslConfigFileName == null) {
        return new HostAwareSslSocketFactory(
                enabledCipherSuites,
                enabledProtocols,
                sslNeedClientAuth, bindAddress);
    } else {
        checkRestrictedFile(sslConfigFileName);
        try {
            // Load the SSL keystore properties from the config file
            Properties p = new Properties();
            try (InputStream in = new FileInputStream(sslConfigFileName)) {
                BufferedInputStream bin = new BufferedInputStream(in);
                p.load(bin);
            }
            String keyStore =
                    p.getProperty("javax.net.ssl.keyStore");
            String keyStorePassword =
                    p.getProperty("javax.net.ssl.keyStorePassword", "");
            String trustStore =
                    p.getProperty("javax.net.ssl.trustStore");
            String trustStorePassword =
                    p.getProperty("javax.net.ssl.trustStorePassword", "");

            char[] keyStorePasswd = null;
            if (keyStorePassword.length() != 0) {
                keyStorePasswd = keyStorePassword.toCharArray();
            }

            char[] trustStorePasswd = null;
            if (trustStorePassword.length() != 0) {
                trustStorePasswd = trustStorePassword.toCharArray();
            }

            KeyStore ks = null;
            if (keyStore != null) {
                ks = KeyStore.getInstance(KeyStore.getDefaultType());
                try (FileInputStream ksfis = new FileInputStream(keyStore)) {
                    ks.load(ksfis, keyStorePasswd);
                }
            }
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(
                    KeyManagerFactory.getDefaultAlgorithm());
            kmf.init(ks, keyStorePasswd);

            KeyStore ts = null;
            if (trustStore != null) {
                ts = KeyStore.getInstance(KeyStore.getDefaultType());
                try (FileInputStream tsfis = new FileInputStream(trustStore)) {
                    ts.load(tsfis, trustStorePasswd);
                }
            }
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(
                    TrustManagerFactory.getDefaultAlgorithm());
            tmf.init(ts);

            SSLContext ctx = SSLContext.getInstance("SSL");
            ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

            return new HostAwareSslSocketFactory(
                    ctx,
                    enabledCipherSuites,
                    enabledProtocols,
                    sslNeedClientAuth, bindAddress);
        } catch (Exception e) {
            throw new AgentConfigurationError(AGENT_EXCEPTION, e, e.toString());
        }
    }
}
 
Example 19
Source File: ConnectorBootstrap.java    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
private static SslRMIServerSocketFactory createSslRMIServerSocketFactory(
        String sslConfigFileName,
        String[] enabledCipherSuites,
        String[] enabledProtocols,
        boolean sslNeedClientAuth) {
    if (sslConfigFileName == null) {
        return new SslRMIServerSocketFactory(
                enabledCipherSuites,
                enabledProtocols,
                sslNeedClientAuth);
    } else {
        checkRestrictedFile(sslConfigFileName);
        try {
            // Load the SSL keystore properties from the config file
            Properties p = new Properties();
            try (InputStream in = new FileInputStream(sslConfigFileName)) {
                BufferedInputStream bin = new BufferedInputStream(in);
                p.load(bin);
            }
            String keyStore =
                    p.getProperty("javax.net.ssl.keyStore");
            String keyStorePassword =
                    p.getProperty("javax.net.ssl.keyStorePassword", "");
            String trustStore =
                    p.getProperty("javax.net.ssl.trustStore");
            String trustStorePassword =
                    p.getProperty("javax.net.ssl.trustStorePassword", "");

            char[] keyStorePasswd = null;
            if (keyStorePassword.length() != 0) {
                keyStorePasswd = keyStorePassword.toCharArray();
            }

            char[] trustStorePasswd = null;
            if (trustStorePassword.length() != 0) {
                trustStorePasswd = trustStorePassword.toCharArray();
            }

            KeyStore ks = null;
            if (keyStore != null) {
                ks = KeyStore.getInstance(KeyStore.getDefaultType());
                try (FileInputStream ksfis = new FileInputStream(keyStore)) {
                    ks.load(ksfis, keyStorePasswd);
                }
            }
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(
                    KeyManagerFactory.getDefaultAlgorithm());
            kmf.init(ks, keyStorePasswd);

            KeyStore ts = null;
            if (trustStore != null) {
                ts = KeyStore.getInstance(KeyStore.getDefaultType());
                try (FileInputStream tsfis = new FileInputStream(trustStore)) {
                    ts.load(tsfis, trustStorePasswd);
                }
            }
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(
                    TrustManagerFactory.getDefaultAlgorithm());
            tmf.init(ts);

            SSLContext ctx = SSLContext.getInstance("SSL");
            ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

            return new SslRMIServerSocketFactory(
                    ctx,
                    enabledCipherSuites,
                    enabledProtocols,
                    sslNeedClientAuth);
        } catch (Exception e) {
            throw new AgentConfigurationError(AGENT_EXCEPTION, e, e.toString());
        }
    }
}
 
Example 20
Source File: SSLContextInitializer.java    From trufflesqueak with MIT License 4 votes vote down vote up
private static TrustManagerFactory prepareTrustManagerFactory(final KeyStore store)
                throws GeneralSecurityException {
    final TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    factory.init(store);
    return factory;
}