Example usage for javax.net.ssl KeyManagerFactory getDefaultAlgorithm

List of usage examples for javax.net.ssl KeyManagerFactory getDefaultAlgorithm

Introduction

In this page you can find the example usage for javax.net.ssl KeyManagerFactory getDefaultAlgorithm.

Prototype

public static final String getDefaultAlgorithm() 

Source Link

Document

Obtains the default KeyManagerFactory algorithm name.

Usage

From source file:org.jboss.as.test.integration.logging.syslogserver.TLSSyslogServer.java

/**
 * Creates custom sslContext from keystore and truststore configured in
 *
 * @see org.productivity.java.syslog4j.server.impl.net.tcp.TCPNetSyslogServer#initialize()
 *///from w w w .j  a v  a 2 s .  c o m
@Override
public void initialize() throws SyslogRuntimeException {
    super.initialize();

    if (isBouncyCastleInstalled()) {
        removeBouncyCastle();
        addBouncyCastleOnShutdown = true;
    }

    final SSLTCPNetSyslogServerConfigIF config = (SSLTCPNetSyslogServerConfigIF) this.tcpNetSyslogServerConfig;

    try {
        final char[] keystorePwd = config.getKeyStorePassword().toCharArray();
        final KeyStore keystore = loadKeyStore(config.getKeyStore(), keystorePwd);
        final char[] truststorePassword = config.getTrustStorePassword().toCharArray();
        final KeyStore truststore = loadKeyStore(config.getTrustStore(), truststorePassword);

        final KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keystore, keystorePwd);

        final TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(truststore);

        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
    } catch (Exception e) {
        LOGGER.error("Exception occurred during SSLContext for TLS syslog server initialization", e);
        throw new SyslogRuntimeException(e);
    }
}

From source file:com.msopentech.thali.utilities.universal.HttpKeySSLSocketFactory.java

public HttpKeySSLSocketFactory(final PublicKey serverPublicKey, final KeyStore clientKeyStore,
        final char[] clientPassPhrase)
        throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
    super((KeyStore) null);

    final ThaliPublicKeyComparer thaliPublicKeyComparer = serverPublicKey == null ? null
            : new ThaliPublicKeyComparer(serverPublicKey);

    TrustManager trustManager = new X509TrustManager() {
        @Override/* w w w.  ja  va2s  .  c  o m*/
        public void checkClientTrusted(X509Certificate[] x509Certificates, String authType)
                throws CertificateException {
            throw new RuntimeException(
                    "We should not have gotten a client trusted call, authType was:" + authType);
        }

        @Override
        public void checkServerTrusted(X509Certificate[] x509Certificates, String authType)
                throws CertificateException {
            //TODO: We actually need to restrict authTypes to known secure ones
            if (serverPublicKey == null) {
                return;
            }
            PublicKey rootPublicKey = x509Certificates[x509Certificates.length - 1].getPublicKey();
            if (thaliPublicKeyComparer.KeysEqual(rootPublicKey) == false) {
                throw new RuntimeException("Presented server root key does not match expected server root key");
            }
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };

    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(clientKeyStore, clientPassPhrase);

    sslContext = SSLContext.getInstance("TLS");
    sslContext.init(keyManagerFactory.getKeyManagers(), new TrustManager[] { trustManager },
            new SecureRandom());
    this.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
}

From source file:org.hyperic.util.security.DatabaseSSLProviderImpl.java

private KeyManagerFactory getKeyManagerFactory(final KeyStore keystore, final String password)
        throws KeyStoreException {
    try {/*  w ww . jav a2s . com*/
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keystore, password.toCharArray());
        return keyManagerFactory;
    } catch (NoSuchAlgorithmException e) {
        // no support for algorithm, if this happens we're kind of screwed
        // we're using the default so it should never happen
        throw new KeyStoreException("The algorithm is not supported. Error message:" + e.getMessage());
    } catch (UnrecoverableKeyException e) {
        // invalid password, should never happen
        throw new KeyStoreException("Password for the keystore is invalid. Error message:" + e.getMessage());
    }
}

From source file:org.apache.streams.cassandra.CassandraClient.java

public void start() throws Exception {

    Objects.nonNull(config);//from w ww .jav a 2s .  c o  m

    LOGGER.info("CassandraClient.start {}", config);

    Cluster.Builder builder = Cluster.builder().withPort(config.getPort().intValue()).withoutJMXReporting()
            .withoutMetrics()
            .withSocketOptions(new SocketOptions().setConnectTimeoutMillis(DEFAULT_CONNECT_TIMEOUT_MILLIS * 10)
                    .setReadTimeoutMillis(DEFAULT_READ_TIMEOUT_MILLIS * 10));

    if (config.getSsl() != null && config.getSsl().getEnabled() == true) {

        Ssl ssl = config.getSsl();

        KeyStore ks = KeyStore.getInstance("JKS");

        InputStream trustStore = new FileInputStream(ssl.getTrustStore());
        ks.load(trustStore, ssl.getTrustStorePassword().toCharArray());
        InputStream keyStore = new FileInputStream(ssl.getKeyStore());
        ks.load(keyStore, ssl.getKeyStorePassword().toCharArray());

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

        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(ks, ssl.getKeyStorePassword().toCharArray());

        SSLContext sslContext = SSLContext.getInstance("SSLv3");
        sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

        SSLOptions sslOptions = JdkSSLOptions.builder().withSSLContext(sslContext).build();

        builder = builder.withSSL(sslOptions);
    }

    Collection<InetSocketAddress> addresses = new ArrayList<>();
    for (String h : config.getHosts()) {
        LOGGER.info("Adding Host: {}", h);
        InetSocketAddress socketAddress = new InetSocketAddress(h, config.getPort().intValue());
        addresses.add(socketAddress);
    }
    builder.addContactPointsWithPorts(addresses);

    if (StringUtils.isNotBlank(config.getUser()) && StringUtils.isNotBlank(config.getPassword())) {
        builder.withCredentials(config.getUser(), config.getPassword());
    }
    cluster = builder.build();

    Objects.nonNull(cluster);

    try {
        Metadata metadata = cluster.getMetadata();
        LOGGER.info("Connected to cluster: {}\n", metadata.getClusterName());
        for (Host host : metadata.getAllHosts()) {
            LOGGER.info("Datacenter: {}; Host: {}; Rack: {}\n", host.getDatacenter(), host.getAddress(),
                    host.getRack());
        }
    } catch (Exception e) {
        LOGGER.error("Exception: {}", e);
        throw e;
    }

    try {
        session = cluster.connect();
    } catch (Exception e) {
        LOGGER.error("Exception: {}", e);
        throw e;
    }

    Objects.nonNull(session);

}

From source file:org.reficio.ws.it.util.SslTunnel.java

public void start() {
    try {/*  ww  w  . ja  v  a  2s.c o m*/
        sslContext = SSLContext.getInstance("SSLv3");
        KeyManager[] keyManagers = null;
        TrustManager[] trustManagers = null;

        if (keyStore != null) {
            KeyManagerFactory keyManagerFactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyManagerFactory.init(keyStore, keyStorePassword.toCharArray());
            X509KeyManager defaultKeyManager = (X509KeyManager) keyManagerFactory.getKeyManagers()[0];
            keyManagers = new KeyManager[] { defaultKeyManager };

        }
        if (trustStore != null) {
            TrustManagerFactory trustManagerFactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(trustStore);
            X509TrustManager defaultTrustManager = (X509TrustManager) trustManagerFactory.getTrustManagers()[0];
            trustManagers = new TrustManager[] { defaultTrustManager };
        }

        sslContext.init(keyManagers, trustManagers, new SecureRandom());

        SSLServerSocketFactory socketFactory = sslContext.getServerSocketFactory();
        socket = socketFactory.createServerSocket();
        socket.setReuseAddress(true);
        socket.bind(new InetSocketAddress(sourcePort));
        new ServerThread(socket, run).start();
    } catch (Exception ex) {
        throw new RuntimeException(ex.getMessage(), ex);
    }
}

From source file:com.collabnet.tracker.common.httpClient.SslProtocolSocketFactory.java

private SslProtocolSocketFactory() {
    KeyManager[] keymanagers = null;
    if (System.getProperty(KEY_STORE) != null && System.getProperty(KEY_STORE_PASSWORD) != null) {
        try {//from   w  w  w  .  j  av a 2  s  . c  om
            String type = System.getProperty(KEY_STORE_TYPE, KeyStore.getDefaultType());
            KeyStore keyStore = KeyStore.getInstance(type);
            char[] password = System.getProperty(KEY_STORE_PASSWORD).toCharArray();
            FileInputStream keyStoreInputStream = new FileInputStream(System.getProperty(KEY_STORE));
            keyStore.load(keyStoreInputStream, password);
            keyStoreInputStream.close();
            KeyManagerFactory keyManagerFactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyManagerFactory.init(keyStore, password);
            keymanagers = keyManagerFactory.getKeyManagers();
        } catch (Exception e) {
            log(0, "Could not initialize keystore", e);
        }
    }

    hasKeyManager = keymanagers != null;

    try {
        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(keymanagers, new TrustManager[] { new TrustAllTrustManager() }, null);
        this.socketFactory = sslContext.getSocketFactory();
    } catch (Exception e) {
        log(0, "Could not initialize SSL context", e);
    }
}

From source file:io.github.thefishlive.updater.HttpServer.java

public void run() {
    try {//w  w  w.  ja  v  a 2  s . c  o m
        int port = GitUpdater.port;

        // Set up the HTTP protocol processor
        HttpProcessor httpproc = HttpProcessorBuilder.create().add(new ResponseDate())
                .add(new ResponseServer("GitUpdater/1.0-SNAPSHOT")).add(new ResponseContent())
                .add(new ResponseConnControl()).build();

        // Set up request handlers
        UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper();
        reqistry.register("*", new ResponceHandler());

        // Set up the HTTP service
        HttpService httpService = new HttpService(httpproc, reqistry);

        SSLServerSocketFactory sf = null;
        if (port == 8443) {
            // Initialize SSL context
            ClassLoader cl = getClass().getClassLoader();
            URL url = cl.getResource("my.keystore");
            if (url == null) {
                System.out.println("Keystore not found");
                System.exit(1);
            }
            KeyStore keystore = KeyStore.getInstance("jks");
            keystore.load(url.openStream(), "secret".toCharArray());
            KeyManagerFactory kmfactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmfactory.init(keystore, "secret".toCharArray());
            KeyManager[] keymanagers = kmfactory.getKeyManagers();
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(keymanagers, null, null);
            sf = sslcontext.getServerSocketFactory();
        }

        try {
            Thread t = new RequestListenerThread(port, httpService, sf);
            t.setDaemon(false);
            t.start();
        } catch (BindException ex) {
            System.out.println("Error binding to port " + port);
            System.out.println("Perhaps another server is running on that port");
            return;
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:org.jasig.cas.authentication.FileTrustStoreSslSocketFactory.java

/**
 * Gets the trusted ssl context.//  w  w w. ja  v  a2  s . co m
 *
 * @param trustStoreFile the trust store file
 * @param trustStorePassword the trust store password
 * @param trustStoreType the trust store type
 * @return the trusted ssl context
 */
private static SSLContext getTrustedSslContext(final File trustStoreFile, final String trustStorePassword,
        final String trustStoreType) {
    try {

        if (!trustStoreFile.exists() || !trustStoreFile.canRead()) {
            throw new FileNotFoundException(
                    "Truststore file cannot be located at " + trustStoreFile.getCanonicalPath());
        }
        final FileInputStream casStream = new FileInputStream(trustStoreFile);
        final KeyStore casTrustStore = KeyStore.getInstance(trustStoreType);
        final char[] trustStorePasswordCharArray = trustStorePassword.toCharArray();

        casTrustStore.load(casStream, trustStorePasswordCharArray);
        IOUtils.closeQuietly(casStream);

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

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

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

    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        throw new RuntimeException(e);
    }
}

From source file:org.wso2.andes.configuration.modules.JKSStore.java

public JKSStore(String rootXPath) throws ConfigurationException {

    String locationXPath = rootXPath + relativeXPathForLocation;
    String passwordXPath = rootXPath + relativeXPathForPassword;
    String storeAlgorithmXPath = rootXPath + relativeXPathForStoreAlgorithm;

    String defaultStoreLocation = null;
    String defaultStoreAlgorithm = null;

    if (StringUtils.containsIgnoreCase(rootXPath, "trustStore")) {
        defaultStoreLocation = JKS_BASE_PATH + "wso2carbon.jks";
        defaultStoreAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
    } else {/*from  w w w .j a va 2s  .  co  m*/
        defaultStoreAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
        defaultStoreLocation = JKS_BASE_PATH + "client-truststore.jks";
    }

    // After deriving the full xpaths, the AndesConfigurationManager is used to extract the values for each
    // property.
    storeLocation = AndesConfigurationManager.deriveValidConfigurationValue(locationXPath, String.class,
            defaultStoreLocation);
    password = AndesConfigurationManager.deriveValidConfigurationValue(passwordXPath, String.class,
            DEFAULT_STORE_PASSWORD);
    storeAlgorithm = AndesConfigurationManager.deriveValidConfigurationValue(storeAlgorithmXPath, String.class,
            defaultStoreAlgorithm);
}

From source file:org.appenders.log4j2.elasticsearch.jest.JKSCertInfo.java

@Override
public void applyTo(HttpClientConfig.Builder clientConfigBuilder) {

    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
        clientConfigBuilder.sslSocketFactory(new SSLConnectionSocketFactory(sslContext));
        clientConfigBuilder//  w  w w.ja  va2 s .c  o m
                .httpsIOSessionStrategy(new SSLIOSessionStrategy(sslContext, new NoopHostnameVerifier()));

    } catch (IOException | GeneralSecurityException e) {
        throw new ConfigurationException(configExceptionMessage, e);
    }
}