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:org.eclipse.mylyn.internal.commons.http.PollingSslProtocolSocketFactory.java

public PollingSslProtocolSocketFactory() {
    KeyManager[] keymanagers = null;
    if (System.getProperty(KEY_STORE) != null && System.getProperty(KEY_STORE_PASSWORD) != null) {
        try {// w  w w.j  av  a 2  s  .co  m
            String type = System.getProperty(KEY_STORE_TYPE, KeyStore.getDefaultType());
            KeyStore keyStore = KeyStore.getInstance(type);
            char[] password = System.getProperty(KEY_STORE_PASSWORD).toCharArray();
            keyStore.load(new FileInputStream(System.getProperty(KEY_STORE)), password);
            KeyManagerFactory keyManagerFactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyManagerFactory.init(keyStore, password);
            keymanagers = keyManagerFactory.getKeyManagers();
        } catch (Exception e) {
            CommonsHttpPlugin.log(IStatus.ERROR, "Could not initialize keystore", e); //$NON-NLS-1$
        }
    }

    hasKeyManager = keymanagers != null;

    try {
        SSLContext sslContext = SSLContext.getInstance("SSL"); //$NON-NLS-1$
        sslContext.init(keymanagers, new TrustManager[] { new TrustAllTrustManager() }, null);
        this.socketFactory = sslContext.getSocketFactory();
    } catch (Exception e) {
        CommonsHttpPlugin.log(IStatus.ERROR, "Could not initialize SSL context", e); //$NON-NLS-1$
    }
}

From source file:org.apache.ftpserver.ssl.SSLTestTemplate.java

protected FTPSClient createFTPClient() throws Exception {
    FTPSClient ftpsClient = new FTPSClient(useImplicit());

    FileInputStream fin = new FileInputStream(FTPCLIENT_KEYSTORE);
    KeyStore store = KeyStore.getInstance("jks");
    store.load(fin, KEYSTORE_PASSWORD.toCharArray());
    fin.close();//from ww w .  j  a v  a 2s.co  m

    // initialize key manager factory
    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(store, KEYSTORE_PASSWORD.toCharArray());

    // initialize trust manager factory
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());

    trustManagerFactory.init(store);

    clientKeyManager = keyManagerFactory.getKeyManagers()[0];
    clientTrustManager = trustManagerFactory.getTrustManagers()[0];

    ftpsClient.setKeyManager(clientKeyManager);
    ftpsClient.setTrustManager(clientTrustManager);

    String auth = getAuthValue();
    if (auth != null) {
        ftpsClient.setAuthValue(auth);

        if (auth.equals("SSL")) {
            ftpsClient.setEnabledProtocols(new String[] { "SSLv3" });
        }
    }
    return ftpsClient;
}

From source file:org.cloudcoder.builder2.server.WebappSocketFactory.java

private SSLSocketFactory createSocketFactory() throws IOException, GeneralSecurityException {
    String keyStoreType = "JKS";
    String keystoreFilename = options.getKeystoreFilename();
    InputStream keyStoreInputStream = this.getClass().getClassLoader().getResourceAsStream(keystoreFilename);
    if (keyStoreInputStream == null) {
        throw new IOException("Could not load keystore " + keystoreFilename);
    }//from   w w  w  .  j a v a  2  s  .  c o m

    KeyStore keyStore;
    String keystorePassword = options.getKeystorePassword();
    try {
        keyStore = KeyStore.getInstance(keyStoreType);
        keyStore.load(keyStoreInputStream, keystorePassword.toCharArray());
    } finally {
        IOUtils.closeQuietly(keyStoreInputStream);
    }

    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("PKIX", "SunJSSE");
    //trustManagerFactory.init(trustStore);
    // XXX Load the cert (public key) here instead of the private key?
    trustManagerFactory.init(keyStore);

    // TrustManager
    X509TrustManager x509TrustManager = null;
    for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) {
        if (trustManager instanceof X509TrustManager) {
            x509TrustManager = (X509TrustManager) trustManager;
            break;
        }
    }
    if (x509TrustManager == null) {
        throw new IllegalArgumentException("Cannot find x509TrustManager");
    }

    // KeyManager
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509", "SunJSSE");
    keyManagerFactory.init(keyStore, keystorePassword.toCharArray());
    X509KeyManager x509KeyManager = null;
    for (KeyManager keyManager : keyManagerFactory.getKeyManagers()) {
        if (keyManager instanceof X509KeyManager) {
            x509KeyManager = (X509KeyManager) keyManager;
            break;
        }
    }
    if (x509KeyManager == null) {
        throw new NullPointerException();
    }

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(new KeyManager[] { x509KeyManager }, new TrustManager[] { x509TrustManager }, null);

    return sslContext.getSocketFactory();
}

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

private KeyManagerFactory getKeyManagerFactory(final KeyStore keystore, final String password)
        throws KeyStoreException {
    try {/* w w w . j  a va 2s .  co m*/
        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: " + e, e);
    } catch (UnrecoverableKeyException e) {
        // invalid password, should never happen
        throw new KeyStoreException("Password for the keystore is invalid: " + e, e);
    }
}

From source file:io.hops.hopsworks.api.util.CustomSSLProtocolSocketFactory.java

private KeyManager[] createKeyManagers(final KeyStore keyStore, final String keyPassword)
        throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException {
    if (keyStore == null) {
        LOG.log(Level.SEVERE, "Creating SSL socket but key store is null");
        throw new IllegalArgumentException("KeyStore cannot be null");
    }/* w  ww  .j  a v a  2s . c  o m*/
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(keyStore, keyPassword != null ? keyPassword.toCharArray() : null);

    return kmf.getKeyManagers();
}

From source file:org.thingsboard.rule.engine.mqtt.credentials.CertPemClientCredentials.java

private KeyManagerFactory createAndInitKeyManagerFactory() throws Exception {
    X509Certificate certHolder = readCertFile(cert);
    Object keyObject = readPrivateKeyFile(privateKey);
    char[] passwordCharArray = "".toCharArray();
    if (!StringUtils.isEmpty(password)) {
        passwordCharArray = password.toCharArray();
    }/*  ww w  .j  a  va  2s  . c o  m*/

    JcaPEMKeyConverter keyConverter = new JcaPEMKeyConverter().setProvider("BC");

    PrivateKey privateKey;
    if (keyObject instanceof PEMEncryptedKeyPair) {
        PEMDecryptorProvider provider = new JcePEMDecryptorProviderBuilder().build(passwordCharArray);
        KeyPair key = keyConverter.getKeyPair(((PEMEncryptedKeyPair) keyObject).decryptKeyPair(provider));
        privateKey = key.getPrivate();
    } else if (keyObject instanceof PEMKeyPair) {
        KeyPair key = keyConverter.getKeyPair((PEMKeyPair) keyObject);
        privateKey = key.getPrivate();
    } else if (keyObject instanceof PrivateKey) {
        privateKey = (PrivateKey) keyObject;
    } else {
        throw new RuntimeException("Unable to get private key from object: " + keyObject.getClass());
    }

    KeyStore clientKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    clientKeyStore.load(null, null);
    clientKeyStore.setCertificateEntry("cert", certHolder);
    clientKeyStore.setKeyEntry("private-key", privateKey, passwordCharArray, new Certificate[] { certHolder });

    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(clientKeyStore, passwordCharArray);
    return keyManagerFactory;
}

From source file:org.opendaylight.aaa.cert.impl.CertificateManagerService.java

@Override
public SSLContext getServerContext() {
    String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
    if (algorithm == null) {
        algorithm = "SunX509";
    }/*  w ww  .j a  v a  2s.c  om*/
    SSLContext serverContext = null;
    try {
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
        kmf.init(aaaCertProvider.getODLKeyStore(),
                aaaCertProvider.getOdlKeyStoreInfo().getStorePassword().toCharArray());
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);
        tmf.init(aaaCertProvider.getTrustKeyStore());

        serverContext = SSLContext.getInstance(KeyStoreConstant.TLS_PROTOCOL);
        serverContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    } catch (final NoSuchAlgorithmException | UnrecoverableKeyException | KeyStoreException
            | KeyManagementException e) {
        LOG.error("Error while creating SSLContext ", e);
    }
    return serverContext;
}

From source file:org.candlepin.client.CustomSSLProtocolSocketFactory.java

private SSLContext createCustomSSLContext() {
    try {//ww w . j a v a  2 s .co  m
        KeyManager[] keyManagers = null;
        // Generate key managers off of the identity certificates if
        // doing client auth.
        if (clientAuth) {
            KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
            String[] keyCert = FileUtil.readKeyAndCert(configuration.getConsumerIdentityFilePath());
            kmf.init(PemUtil.pemToKeyStore(keyCert[1], keyCert[0], "password"), "password".toCharArray());
            keyManagers = kmf.getKeyManagers();
        }
        /* and provide them for the SSLContext */
        SSLContext ctx = SSLContext.getInstance("TLS");
        if (configuration.isIgnoreTrustManagers()) {
            ctx.init(keyManagers, Utils.DUMMY_TRUST_MGRS, new SecureRandom());
        } else {
            TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
            KeyStore ks2 = KeyStore.getInstance(KeyStore.getDefaultType());
            ks2.load(null, null);

            ks2.setCertificateEntry("candlepin", PemUtil.readCert("/etc/candlepin/certs/candlepin-ca.crt"));
            // ks2.load(
            // new FileInputStream(configuration.getKeyStoreFileLocation()),
            // passwd);
            tmf.init(ks2);
            ctx.init(keyManagers, tmf.getTrustManagers(), new SecureRandom());
        }

        return ctx;
    } catch (Exception e) {
        e.printStackTrace();
        throw new HttpClientError(e.getMessage());
    }
}

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

public void start() throws Exception {

    Objects.nonNull(config);//from  ww w .  ja  v a2  s . 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: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 ww  w  . ja v a2 s  . co  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);
    }
}