Example usage for javax.net.ssl KeyManagerFactory init

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

Introduction

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

Prototype

public final void init(KeyStore ks, char[] password)
        throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException 

Source Link

Document

Initializes this factory with a source of key material.

Usage

From source file:net.di2e.ecdr.source.rest.TLSUtil.java

public static void setTLSOptions(WebClient client, boolean disableCNCheck) {
    ClientConfiguration clientConfiguration = WebClient.getConfig(client);

    HTTPConduit httpConduit = clientConfiguration.getHttpConduit();

    String keyStorePath = System.getProperty(SSL_KEYSTORE_JAVA_PROPERTY);
    String keyStorePassword = System.getProperty(SSL_KEYSTORE_PASSWORD_JAVA_PROPERTY);
    if (StringUtils.isNotBlank(keyStorePath) && StringUtils.isNotBlank(keyStorePassword)) {
        try {/*from  w  w w  .j a  v a 2  s  .  c o m*/
            TLSClientParameters tlsParams = new TLSClientParameters();
            LOGGER.debug("Setting disable of CN check on client URL {} to [{}]", client.getCurrentURI(),
                    disableCNCheck);
            tlsParams.setDisableCNCheck(disableCNCheck);

            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());

            // add the keystore if it exists
            File keystore = new File(keyStorePath);
            if (keystore.exists() && keyStorePassword != null) {
                FileInputStream fis = new FileInputStream(keystore);
                try {
                    LOGGER.debug("Loading keyStore {}", keystore);
                    keyStore.load(fis, keyStorePassword.toCharArray());
                } catch (IOException e) {
                    LOGGER.error("Unable to load keystore. {}", keystore, e);
                } catch (CertificateException e) {
                    LOGGER.error("Unable to load certificates from keystore. {}", keystore, e);
                } finally {
                    IOUtils.closeQuietly(fis);
                }
                KeyManagerFactory keyFactory = KeyManagerFactory
                        .getInstance(KeyManagerFactory.getDefaultAlgorithm());
                keyFactory.init(keyStore, keyStorePassword.toCharArray());
                KeyManager[] km = keyFactory.getKeyManagers();
                tlsParams.setKeyManagers(km);
            }

            httpConduit.setTlsClientParameters(tlsParams);
        } catch (KeyStoreException e) {
            LOGGER.error("Unable to read keystore: ", e);
        } catch (NoSuchAlgorithmException e) {
            LOGGER.error("Problems creating SSL socket. Usually this is "
                    + "referring to the certificate sent by the server not being trusted by the client.", e);
        } catch (FileNotFoundException e) {
            LOGGER.error("Unable to locate one of the SSL stores: {} | {}", keyStorePath, e);
        } catch (UnrecoverableKeyException e) {
            LOGGER.error("Unable to read keystore: ", e);
        }
    }
}

From source file:ddf.security.common.util.CommonSSLFactory.java

/**
 * Creates a new SSLSocketFactory from a truststore and keystore. This is used during SSL
 * communication.//from w  w  w  .j ava 2s  . c om
 * 
 * @param trustStoreLoc
 *            File path to the truststore.
 * @param trustStorePass
 *            Password to the truststore.
 * @param keyStoreLoc
 *            File path to the keystore.
 * @param keyStorePass
 *            Password to the keystore.
 * @return new SSLSocketFactory instance containing the trust and key stores.
 * @throws IOException
 */
public static SSLSocketFactory createSocket(String trustStoreLoc, String trustStorePass, String keyStoreLoc,
        String keyStorePass) throws IOException {
    String methodName = "createSocket";
    logger.debug("ENTERING: " + methodName);

    try {
        logger.debug("trustStoreLoc = " + trustStoreLoc);
        FileInputStream trustFIS = new FileInputStream(trustStoreLoc);
        logger.debug("keyStoreLoc = " + keyStoreLoc);
        FileInputStream keyFIS = new FileInputStream(keyStoreLoc);

        // truststore stuff
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        try {
            logger.debug("Loading trustStore");
            trustStore.load(trustFIS, trustStorePass.toCharArray());
        } catch (CertificateException e) {
            throw new IOException("Unable to load certificates from truststore. " + trustStoreLoc, e);
        } finally {
            IOUtils.closeQuietly(trustFIS);
        }

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(trustStore);
        logger.debug("trust manager factory initialized");

        // keystore stuff
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        try {
            logger.debug("Loading keyStore");
            keyStore.load(keyFIS, keyStorePass.toCharArray());
        } catch (CertificateException e) {
            throw new IOException("Unable to load certificates from keystore. " + keyStoreLoc, e);
        } finally {
            IOUtils.closeQuietly(keyFIS);
        }
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(keyStore, keyStorePass.toCharArray());
        logger.debug("key manager factory initialized");

        // ssl context
        SSLContext sslCtx = SSLContext.getInstance("TLS");
        sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
        sslCtx.getDefaultSSLParameters().setNeedClientAuth(true);
        sslCtx.getDefaultSSLParameters().setWantClientAuth(true);
        logger.debug(exiting + methodName);

        return sslCtx.getSocketFactory();
    } catch (KeyManagementException e) {
        logger.debug(exiting + methodName);
        throw new IOException("Unable to initialize the SSL context.", e);
    } catch (NoSuchAlgorithmException e) {
        logger.debug(exiting + methodName);
        throw new IOException(
                "Problems creating SSL socket. Usually this is "
                        + "referring to the certificate sent by the server not being trusted by the client.",
                e);
    } catch (UnrecoverableKeyException e) {
        logger.debug(exiting + methodName);
        throw new IOException("Unable to load keystore. " + keyStoreLoc, e);
    } catch (KeyStoreException e) {
        logger.debug(exiting + methodName);
        throw new IOException("Unable to read keystore. " + keyStoreLoc, e);
    }
}

From source file:io.dropwizard.revolver.http.RevolverHttpClientFactory.java

private static SSLContext getSSLContext(final String keyStorePath, final String keyStorePassword)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException,
        KeyManagementException, UnrecoverableKeyException {
    final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    try (InputStream instream = RevolverHttpClientFactory.class.getClassLoader()
            .getResourceAsStream(keyStorePath)) {
        keyStore.load(instream, keyStorePassword.toCharArray());
    }/*from  w  ww  .jav  a2 s.  co m*/
    final TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(keyStore);
    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, keyStorePassword.toCharArray());
    final SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(),
            new SecureRandom());
    return sslContext;
}

From source file:ninja.standalone.StandaloneHelper.java

static public SSLContext createSSLContext(URI keystoreUri, char[] keystorePassword, URI truststoreUri,
        char[] truststorePassword) throws Exception {

    // load keystore
    KeyStore keystore = loadKeyStore(keystoreUri, keystorePassword);
    KeyManager[] keyManagers;/*  www  .j  a  va 2  s .co m*/
    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keystore, keystorePassword);
    keyManagers = keyManagerFactory.getKeyManagers();

    // load truststore
    KeyStore truststore = loadKeyStore(truststoreUri, truststorePassword);
    TrustManager[] trustManagers;
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(truststore);
    trustManagers = trustManagerFactory.getTrustManagers();

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

    return sslContext;
}

From source file:com.openmeap.util.SSLUtils.java

public static KeyManager[] getDefaultKeyManagers(KeyStore keyStore, String password)
        throws NoSuchAlgorithmException, UnrecoverableKeyException, KeyStoreException {

    // now we have to initialize the KeyManagers too
    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, password.toCharArray());
    return keyManagerFactory.getKeyManagers();
}

From source file:org.apache.ranger.services.nifi.client.NiFiConnectionMgr.java

private static SSLContext createSslContext(final String keystore, final char[] keystorePasswd,
        final String keystoreType, final String truststore, final char[] truststorePasswd,
        final String truststoreType, final String protocol) throws KeyStoreException, IOException,
        NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException, KeyManagementException {

    // prepare the keystore
    final KeyStore keyStore = KeyStore.getInstance(keystoreType);
    try (final InputStream keyStoreStream = new FileInputStream(keystore)) {
        keyStore.load(keyStoreStream, keystorePasswd);
    }//from ww  w. ja  v a  2  s. c o m
    final KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, keystorePasswd);

    // prepare the truststore
    final KeyStore trustStore = KeyStore.getInstance(truststoreType);
    try (final InputStream trustStoreStream = new FileInputStream(truststore)) {
        trustStore.load(trustStoreStream, truststorePasswd);
    }
    final TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(trustStore);

    // initialize the ssl context
    final SSLContext sslContext = SSLContext.getInstance(protocol);
    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(),
            new SecureRandom());
    return sslContext;
}

From source file:org.wso2.carbon.andes.extensions.device.mgt.mqtt.authorization.client.OAuthRequestInterceptor.java

private static SSLSocketFactory initSSLConnection(KeyStore keyStore, String keyStorePassword,
        KeyStore trustStore)//from   w  ww  .j  a va  2 s .  co  m
        throws NoSuchAlgorithmException, UnrecoverableKeyException, KeyStoreException, KeyManagementException {
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
    keyManagerFactory.init(keyStore, keyStorePassword.toCharArray());
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
    trustManagerFactory.init(trustStore);

    // Create and initialize SSLContext for HTTPS communication
    SSLContext sslContext = SSLContext.getInstance("SSLv3");
    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
    SSLContext.setDefault(sslContext);
    return sslContext.getSocketFactory();
}

From source file:com.oneis.common.utils.SSLCertificates.java

public static SSLContext load(String keysDirectory, String certsName, String clientCAName, boolean quiet)
        throws Exception {
    // For some indiciation of what's going on early in the boot process
    if (!quiet) {
        System.out.println("Loading " + certsName + " SSL certificates from " + keysDirectory);
    }/*  ww w  . j  av  a2 s  .  co  m*/

    // Get filenames
    String keyPathname = keysDirectory + "/" + certsName + ".key";
    String certPathname = keysDirectory + "/" + certsName + ".crt";
    final String intermediateCertPathnameBase = keysDirectory + "/" + certsName + "-intermediate";
    String clientCAPathname = null;
    if (clientCAName != null) {
        clientCAPathname = keysDirectory + "/" + clientCAName + ".crt";
    }

    if (!new File(keyPathname).exists()) {
        System.out.println("Doesn't exist: " + keyPathname);
        return null;
    }
    if (!new File(certPathname).exists()) {
        System.out.println("Doesn't exist: " + certPathname);
        return null;
    }
    if (clientCAPathname != null) {
        if (!new File(clientCAPathname).exists()) {
            System.out.println("Doesn't exist: " + clientCAPathname);
            return null;
        }
    }

    char[] nullPassword = {};

    PrivateKey privateKey = readPEMPrivateKey(keyPathname);

    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    // Server certificate
    ArrayList<java.security.cert.Certificate> certList = new ArrayList<java.security.cert.Certificate>(4);
    java.security.cert.Certificate cert = cf.generateCertificate(readPEM(certPathname));
    certList.add(cert);
    // Optional intermediate certificates
    int intermediateCounter = 1;
    while (true) {
        String intermediateCertPathname = intermediateCertPathnameBase;
        if (intermediateCounter != 1) {
            intermediateCertPathname += "-" + intermediateCounter;
        }
        intermediateCounter++;
        intermediateCertPathname += ".crt";
        if (new File(intermediateCertPathname).exists()) {
            certList.add(cf.generateCertificate(readPEM(intermediateCertPathname)));
        } else {
            // End of cert list
            break;
        }
    }
    // Optional client CA certificate
    java.security.cert.Certificate clientCACert = null;
    if (clientCAPathname != null) {
        clientCACert = cf.generateCertificate(readPEM(clientCAPathname));
    }
    if (clientCAName != null && clientCACert == null) {
        throw new RuntimeException("Logic error, failed to load client CA cert when required");
    }

    KeyStore ks = KeyStore.getInstance("JKS", "SUN");
    ks.load(null, nullPassword);
    ks.setKeyEntry("ONEIS", (Key) privateKey, "".toCharArray(),
            certList.toArray(new java.security.cert.Certificate[certList.size()]));

    if (clientCACert != null) {
        KeyStore.TrustedCertificateEntry tce = new KeyStore.TrustedCertificateEntry(clientCACert);
        ks.setEntry("CLIENTCA", tce, null);
    }

    // Generate some random Java API stuff, just for entertainment
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
    kmf.init(ks, nullPassword);
    TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
    tmf.init(ks);

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

    if (!quiet) {
        System.out.println(" - server cert chain length " + certList.size()
                + (clientCACert != null ? ", requires client cert" : ", public server"));
    }
    return sslContext;
}

From source file:com.wso2telco.identity.application.authentication.endpoint.util.MutualSSLClient.java

/**
 * create basic SSL connection factory/*  w  ww  .j  a va  2 s.  c  om*/
 *
 * @throws java.security.NoSuchAlgorithmException
 * @throws java.security.KeyStoreException
 * @throws java.security.KeyManagementException
 * @throws java.io.IOException
 * @throws java.security.UnrecoverableKeyException
 */
public static void initMutualSSLConnection() throws NoSuchAlgorithmException, KeyStoreException,
        KeyManagementException, IOException, UnrecoverableKeyException {

    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KEY_MANAGER_TYPE);
    keyManagerFactory.init(keyStore, keyStorePassword.toCharArray());
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TRUST_MANAGER_TYPE);
    trustManagerFactory.init(trustStore);
    SSLContext sslContext = SSLContext.getInstance(PROTOCOL);
    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
    sslSocketFactory = sslContext.getSocketFactory();
}

From source file:com.geotrackin.gpslogger.senders.ftp.Ftp.java

public synchronized static boolean Upload(String server, String username, String password, String directory,
        int port, boolean useFtps, String protocol, boolean implicit, InputStream inputStream,
        String fileName) {/*ww w.  ja  v  a 2 s.  c o m*/
    FTPClient client = null;

    try {
        if (useFtps) {
            client = new FTPSClient(protocol, implicit);

            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmf.init(null, null);
            KeyManager km = kmf.getKeyManagers()[0];
            ((FTPSClient) client).setKeyManager(km);
        } else {
            client = new FTPClient();
        }

    } catch (Exception e) {
        tracer.error("Could not create FTP Client", e);
        return false;
    }

    try {
        tracer.debug("Connecting to FTP");
        client.connect(server, port);
        showServerReply(client);

        tracer.debug("Logging in to FTP server");
        if (client.login(username, password)) {
            client.enterLocalPassiveMode();
            showServerReply(client);

            tracer.debug("Uploading file to FTP server " + server);

            tracer.debug("Checking for FTP directory " + directory);
            FTPFile[] existingDirectory = client.listFiles(directory);
            showServerReply(client);

            if (existingDirectory.length <= 0) {
                tracer.debug("Attempting to create FTP directory " + directory);
                //client.makeDirectory(directory);
                ftpCreateDirectoryTree(client, directory);
                showServerReply(client);

            }

            client.changeWorkingDirectory(directory);
            boolean result = client.storeFile(fileName, inputStream);
            inputStream.close();
            showServerReply(client);
            if (result) {
                tracer.debug("Successfully FTPd file " + fileName);
            } else {
                tracer.debug("Failed to FTP file " + fileName);
                return false;
            }

        } else {
            tracer.debug("Could not log in to FTP server");
            return false;
        }

    } catch (Exception e) {
        tracer.error("Could not connect or upload to FTP server.", e);
        return false;
    } finally {
        try {
            tracer.debug("Logging out of FTP server");
            client.logout();
            showServerReply(client);

            tracer.debug("Disconnecting from FTP server");
            client.disconnect();
            showServerReply(client);
        } catch (Exception e) {
            tracer.error("Could not logout or disconnect", e);
            return false;
        }
    }

    return true;
}