Example usage for javax.net.ssl KeyManagerFactory getKeyManagers

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

Introduction

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

Prototype

public final KeyManager[] getKeyManagers() 

Source Link

Document

Returns one key manager for each type of key material.

Usage

From source file:net.sf.jsignpdf.ssl.SSLInitializer.java

/**
 * @param options/*from w w  w  . java2s  . c  o  m*/
 * @throws NoSuchAlgorithmException
 * @throws IOException
 * @throws CertificateException
 * @throws KeyStoreException
 * @throws KeyManagementException
 * @throws UnrecoverableKeyException
 */
public static void init(BasicSignerOptions options) throws NoSuchAlgorithmException, KeyManagementException,
        KeyStoreException, CertificateException, IOException, UnrecoverableKeyException {
    KeyManager[] km = null;
    if (options != null && options.getTsaServerAuthn() == ServerAuthentication.CERTIFICATE) {
        char[] pwd = null;
        if (StringUtils.isNotEmpty(options.getTsaCertFilePwd())) {
            pwd = options.getTsaCertFilePwd().toCharArray();
        }
        LOGGER.info(Constants.RES.get("ssl.keymanager.init", options.getTsaCertFile()));
        final String ksType = StringUtils.defaultIfBlank(options.getTsaCertFileType(), "PKCS12");
        KeyStore keyStore = KeyStoreUtils.loadKeyStore(ksType, options.getTsaCertFile(), pwd);
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, pwd);
        km = keyManagerFactory.getKeyManagers();
    }
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(km, TRUST_MANAGERS, null);

    HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
}

From source file:org.openhealthtools.openatna.net.ConnectionCertificateHandler.java

/**
 * Creates keymanagers from a keystore.//  w  w  w .  j a  va  2 s . c o m
 */
public static KeyManager[] createKeyManagers(final KeyStore keystore, final String password)
        throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {
    if (keystore == null) {
        throw new IllegalArgumentException("Keystore may not be null");
    }
    log.debug("Initializing key manager");
    KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmfactory.init(keystore, password != null ? password.toCharArray() : null);
    return kmfactory.getKeyManagers();
}

From source file:spade.client.CommandLine.java

private static void setupClientSSLContext() throws Exception {
    SecureRandom secureRandom = new SecureRandom();
    secureRandom.nextInt();//w  w  w.  ja va 2  s  .c om

    TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
    tmf.init(serverKeyStorePublic);
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
    kmf.init(clientKeyStorePrivate, "private".toCharArray());

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), secureRandom);
    sslSocketFactory = sslContext.getSocketFactory();
}

From source file:org.openo.nfvo.vnfmadapter.service.csm.connect.AbstractSslContext.java

protected static KeyManager[] createKeyManager(JSONObject sslConf) {
    KeyManager[] kms = null;/*w w w. j a v  a  2s.  c  om*/
    try {
        String CERT_STORE = "etc/conf/server.p12";
        String CERT_STORE_PASSWORD = "Changeme_123";
        String KEY_STORE_TYPE = "PKCS12";
        if (sslConf != null) {
            CERT_STORE = sslConf.getString("keyStore");
            CERT_STORE_PASSWORD = sslConf.getString("keyStorePass");
            KEY_STORE_TYPE = sslConf.getString("keyStoreType");
        }
        // load jks file
        FileInputStream f_certStore = new FileInputStream(CERT_STORE);
        KeyStore ks = KeyStore.getInstance(KEY_STORE_TYPE);
        ks.load(f_certStore, CERT_STORE_PASSWORD.toCharArray());
        f_certStore.close();

        // init and create
        String alg = KeyManagerFactory.getDefaultAlgorithm();
        KeyManagerFactory kmFact = KeyManagerFactory.getInstance(alg);
        kmFact.init(ks, CERT_STORE_PASSWORD.toCharArray());

        kms = kmFact.getKeyManagers();
    } catch (Exception e) {
        LOG.error("create KeyManager fail!", e);
    }
    return kms;
}

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: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;/*  w  ww.  j  a  v  a  2  s.  c  om*/
    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:org.elasticsearch.client.RestClientBuilderIntegTests.java

private static SSLContext getSslContext() throws Exception {
    SSLContext sslContext = SSLContext.getInstance("TLS");
    try (InputStream in = RestClientBuilderIntegTests.class.getResourceAsStream("/testks.jks")) {
        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(in, "password".toCharArray());
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(keyStore, "password".toCharArray());
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
        tmf.init(keyStore);/* w  w  w  . j  av a  2s . co m*/
        sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    }
    return sslContext;
}

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) {/*w w w  .j av  a2s  . 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;
}

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 {/*w w w . j av a 2 s. co 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:org.openremote.android.console.net.SelfCertificateSSLSocketFactory.java

/**
 * Creates a new SelfCertificateSSLSocket object.
 * /* www .j  a v a 2s .co  m*/
 * @return the SSL context
 * 
 * @throws IOException Signals that an I/O exception has occurred.
 */
private static SSLContext createEasySSLContext(Context context) throws IOException {
    TrustManager easyTrustManager = new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
        }

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

    try {
        ORKeyStore keystore = ORKeyStore.getInstance(context);
        KeyManager[] managers = null;

        //keystore.fillKeyStore();
        //keystore.saveKeyStore();

        if (!keystore.isEmpty()) {
            KeyManagerFactory keyManagerFactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyManagerFactory.init(keystore.getKeyStore(), "password".toCharArray());

            managers = keyManagerFactory.getKeyManagers();
        }

        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(managers, new TrustManager[] { easyTrustManager }, null);
        return sslcontext;
    } catch (Exception e) {
        throw new IOException(e.getMessage());
    }
}