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:gobblin.security.ssl.SSLContextFactory.java

/**
 * Create a {@link SSLContext} instance/*from  w w w  . j a v  a  2 s  . c o m*/
 *
 * @param keyStoreFile a p12 or jks file depending on key store type
 * @param keyStorePassword password to access the key store
 * @param keyStoreType type of key store
 * @param trustStoreFile a jks file
 * @param trustStorePassword password to access the trust store
 */
public static SSLContext createInstance(File keyStoreFile, String keyStorePassword, String keyStoreType,
        File trustStoreFile, String trustStorePassword) {
    if (!keyStoreType.equalsIgnoreCase(P12_STORE_TYPE_NAME)
            && !keyStoreType.equalsIgnoreCase(JKS_STORE_TYPE_NAME)) {
        throw new IllegalArgumentException("Unsupported keyStoreType: " + keyStoreType);
    }

    try {
        // Load KeyStore
        KeyStore keyStore = KeyStore.getInstance(keyStoreType);
        keyStore.load(toInputStream(keyStoreFile), keyStorePassword.toCharArray());

        // Load TrustStore
        KeyStore trustStore = KeyStore.getInstance(JKS_STORE_TYPE_NAME);
        trustStore.load(toInputStream(trustStoreFile), trustStorePassword.toCharArray());

        // Set KeyManger from keyStore
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(DEFAULT_ALGORITHM);
        kmf.init(keyStore, keyStorePassword.toCharArray());

        // Set TrustManager from trustStore
        TrustManagerFactory trustFact = TrustManagerFactory.getInstance(DEFAULT_ALGORITHM);
        trustFact.init(trustStore);

        // Set Context to TLS and initialize it
        SSLContext sslContext = SSLContext.getInstance(DEFAULT_PROTOCOL);
        sslContext.init(kmf.getKeyManagers(), trustFact.getTrustManagers(), null);

        return sslContext;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

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

/**
 * Creates keymanagers from a keystore./*from   w w  w . jav  a  2s  .com*/
 */
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:com.amalto.workbench.utils.SSLContextProvider.java

private static KeyManager[] buildKeyManagers(String path, String storePass, String keytype)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException,
        UnrecoverableKeyException {
    InputStream stream = null;/*from   w  w  w  .j ava2s  . c  o m*/
    try {
        if (StringUtils.isEmpty(path)) {
            return null;
        }
        if (!new File(path).exists()) {
            throw new KeyStoreException(Messages.bind(Messages.noKeystoreFile_error, path));
        }
        stream = new FileInputStream(path);

        KeyStore tks = KeyStore.getInstance(keytype);
        tks.load(stream, storePass.toCharArray());

        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); //$NON-NLS-1$
        kmf.init(tks, storePass.toCharArray());

        return kmf.getKeyManagers();
    } finally {
        IOUtils.closeQuietly(stream);
    }
}

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

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

    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) {
        e.printStackTrace();
    }

    try {
        Utilities.LogDebug("Connecting to FTP");
        client.connect(server, port);

        Utilities.LogDebug("Logging in to FTP server");
        if (client.login(username, password)) {
            client.enterLocalPassiveMode();

            Utilities.LogDebug("Uploading file to FTP server");

            FTPFile[] existingDirectory = client.listFiles("GPSLogger");

            if (existingDirectory.length <= 0) {
                client.makeDirectory("GPSLogger");
            }

            client.changeWorkingDirectory("GPSLogger");
            boolean result = client.storeFile(fileName, inputStream);
            inputStream.close();
            if (result) {
                Utilities.LogDebug("Successfully FTPd file");
            } else {
                Utilities.LogDebug("Failed to FTP file");
            }

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

    } catch (Exception e) {
        Utilities.LogError("Could not connect or upload to FTP server.", e);
    } finally {
        try {
            Utilities.LogDebug("Logging out of FTP server");
            client.logout();

            Utilities.LogDebug("Disconnecting from FTP server");
            client.disconnect();
        } catch (Exception e) {
            Utilities.LogError("Could not logout or disconnect", e);
        }
    }

    return true;
}

From source file:org.apache.hadoop.gateway.jetty.JettyHttpsTest.java

private static KeyManager[] createKeyManagers(String keyStoreType, String keyStorePath, String keyStorePassword)
        throws Exception {
    KeyStore keyStore = loadKeyStore(keyStoreType, keyStorePath, keyStorePassword);
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(keyStore, keyStorePassword.toCharArray());
    return kmf.getKeyManagers();
}

From source file:org.wso2.carbon.apimgt.integration.client.util.Utils.java

private static SSLSocketFactory initSSLConnection(KeyStore keyStore, String keyStorePassword,
        KeyStore trustStore)/*from w w w.  ja  v a2 s .c  o m*/
        throws NoSuchAlgorithmException, UnrecoverableKeyException, KeyStoreException, KeyManagementException {
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KEY_MANAGER_TYPE);
    keyManagerFactory.init(keyStore, keyStorePassword.toCharArray());
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TRUST_MANAGER_TYPE);
    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:org.wisdom.engine.ssl.FakeKeyStore.java

public static KeyManagerFactory keyManagerFactory(File root) {
    try {/*from   w  ww .j ava2s.  c  o  m*/
        KeyStore keyStore = KeyStore.getInstance("JKS");
        File keyStoreFile = new File(root, KEYSTORE_PATH);
        if (!keyStoreFile.exists()) {
            generateAndStoreKeyStore(keyStore, keyStoreFile);
        } else {
            loadKeyStore(keyStore, keyStoreFile);
        }
        // Load the key and certificate into a key manager factory
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(keyStore, "".toCharArray());
        return kmf;
    } catch (Exception e) {
        LOGGER.error("Cannot generate or read the fake key store", e);
        return null;
    }
}

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

/**
 * @param options/*from www  .  j  a  v  a  2 s  .com*/
 * @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.openo.nfvo.vnfmadapter.service.csm.connect.AbstractSslContext.java

protected static KeyManager[] createKeyManager(JSONObject sslConf) {
    KeyManager[] kms = null;// w  w  w  . jav  a 2s.com
    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.apporiented.hermesftp.utils.SecurityUtil.java

/**
 * Create the security context required for SSL communication.
 * //from w  w w . j av a2s . c o  m
 * @param keyStoreFile The name of the keystore file.
 * @param keyStorePassword The password for the keystore.
 * @return The context.
 * @throws FtpConfigException Thrown on error in configuration.
 */
public static SSLContext createSslContext(String keyStoreFile, char[] keyStorePassword)
        throws FtpConfigException {
    SSLContext sslContext;
    try {
        /* Get keystore file and password */
        InputStream ksInputStream = getKeyStoreInputStream(keyStoreFile);

        /*
         * Get the java keystore object an key manager. A keystore is where keys and
         * certificates are kept.
         */
        KeyStore keystore = KeyStore.getInstance("JKS");
        keystore.load(ksInputStream, keyStorePassword);
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(keystore, keyStorePassword);

        /*
         * An SSLContext is an environment for implementing JSSE. It is used to create a
         * ServerSocketFactory
         */
        sslContext = SSLContext.getInstance("SSL");
        sslContext.init(kmf.getKeyManagers(), null, null);
    } catch (KeyManagementException e) {

        throw new SecurityException("A key management authorization problem occurred.");
    } catch (FileNotFoundException e) {
        throw new SecurityException("The key store file could not be found.");
    } catch (KeyStoreException e) {
        throw new SecurityException("A key store problem occurred.");
    } catch (NoSuchAlgorithmException e) {
        throw new SecurityException("The hash algorithm is not supported.");
    } catch (CertificateException e) {
        throw new SecurityException("Certificate could not be loaded.");
    } catch (UnrecoverableKeyException e) {
        throw new SecurityException("Key store cannot be recovered.");
    } catch (IOException e) {
        throw new SecurityException("Reading the key store failed.");
    }
    return sslContext;
}