Example usage for javax.net.ssl KeyManagerFactory getInstance

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

Introduction

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

Prototype

public static final KeyManagerFactory getInstance(String algorithm) throws NoSuchAlgorithmException 

Source Link

Document

Returns a KeyManagerFactory object that acts as a factory for key managers.

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()
 *///w ww  . j a  va 2  s.  co 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:inet.encode.SecureMonitor.java

private static void createHttpsServer() {
    try {//from www  .  jav  a  2  s  .  c  o m
        server = HttpsServer.create(new InetSocketAddress(MONITOR_SERVER_PORT), 0);

        SSLContext sslContext = SSLContext.getInstance("TLS");
        // initialise the keystore
        char[] password = Encoder.KEY_STORE_PASS_PHRASE.toCharArray();
        KeyStore ks = KeyStore.getInstance("JKS");
        FileInputStream fis = new FileInputStream(Encoder.KEY_STORE_PATH);
        ks.load(fis, password);

        // setup the key manager factory
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ks, password);

        // setup the trust manager factory
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
        tmf.init(ks);

        // setup the HTTPS context and parameters
        sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

        server.setHttpsConfigurator(new HttpsConfigurator(sslContext));
        server.setExecutor(java.util.concurrent.Executors.newCachedThreadPool());
        server.start();
    } catch (Exception ex) {
        Logger.log(ex);
    }
}

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//from   w  w w. ja  v  a2s .  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.kuali.mobility.push.factory.iOSConnectionFactory.java

@Override
public SSLSocket makeObject() throws Exception {
    SSLSocket socket = null;/*from ww  w.  j  av  a 2s . c o  m*/
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    keyStore.load(certPath.getInputStream(), certPassword.toCharArray());
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("sunx509");
    keyManagerFactory.init(keyStore, certPassword.toCharArray());
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("sunx509");
    trustManagerFactory.init(keyStore);
    SSLContext sslCtx = SSLContext.getInstance("TLS");
    sslCtx.init(keyManagerFactory.getKeyManagers(), null, null);
    SSLSocketFactory sslSocketFactory = sslCtx.getSocketFactory();
    socket = (SSLSocket) sslSocketFactory.createSocket(host, port);
    socket.startHandshake();
    return socket;
}

From source file:org.kuali.mobility.push.factory.iOSFeedbackConnectionFactory.java

@Override
public SSLSocket makeObject() throws Exception {
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    keyStore.load(certPath.getInputStream(), certPassword.toCharArray());
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("sunx509");
    keyManagerFactory.init(keyStore, certPassword.toCharArray());
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("sunx509");
    trustManagerFactory.init(keyStore);// w w  w . j a  va  2s . com
    SSLContext sslCtx = SSLContext.getInstance("TLS");
    sslCtx.init(keyManagerFactory.getKeyManagers(), null, null);
    SSLSocketFactory sslSocketFactory = sslCtx.getSocketFactory();
    SSLSocket socket = (SSLSocket) sslSocketFactory.createSocket(host, port);
    socket.startHandshake();
    return socket;
}

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

private KeyManagerFactory getKeyManagerFactory(final KeyStore keystore, final String password)
        throws KeyStoreException {
    try {/*from  www  .j  a va 2 s  . c  om*/
        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.reficio.ws.it.util.SslTunnel.java

public void start() {
    try {//from www .j  a va 2s . co 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  .  ja v  a 2 s  . c o  m
            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:org.apache.streams.cassandra.CassandraClient.java

public void start() throws Exception {

    Objects.nonNull(config);// w w  w  .  j  ava2s .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:io.github.thefishlive.updater.HttpServer.java

public void run() {
    try {//from ww  w  . j  a v  a2 s .co  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();
    }
}