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.wso2.carbon.inbound.ibmmq.poll.IbmMqConsumer.java

public void sslConnection() {
    String keyStoreLocation = properties.getProperty(ibmMqConstant.SSL_KEYSTORE_LOCATION);
    String keyStoreType = properties.getProperty(ibmMqConstant.SSL_KEYSTORE_TYPE);
    String keyStorePassword = properties.getProperty(ibmMqConstant.SSL_KEYSTORE_PASSWORD);
    String trustStoreLocation = properties.getProperty(ibmMqConstant.SSL_TRUSTSTORE_LOCATION);
    String trustStoreType = properties.getProperty(ibmMqConstant.SSL_TRUSTSTORE_TYPE);
    String sslVersion = properties.getProperty(ibmMqConstant.SSL_VERSION);
    String sslFipsRequired = properties.getProperty(ibmMqConstant.SSL_FIPS);
    String sslCipherSuite = properties.getProperty(ibmMqConstant.SSL_CIPHERSUITE);
    boolean sslFips = Boolean.parseBoolean(sslFipsRequired);
    try {/*  w  w w .  ja v a 2 s.  c  o  m*/
        char[] keyPassphrase = keyStorePassword.toCharArray();
        KeyStore ks = KeyStore.getInstance(keyStoreType);
        ks.load(new FileInputStream(keyStoreLocation), keyPassphrase);
        KeyStore trustStore = KeyStore.getInstance(trustStoreType);
        trustStore.load(new FileInputStream(trustStoreLocation), null);

        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());

        trustManagerFactory.init(trustStore);
        keyManagerFactory.init(ks, keyPassphrase);
        SSLContext sslContext = SSLContext.getInstance(sslVersion);
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
        MQEnvironment.sslSocketFactory = sslContext.getSocketFactory();
        MQEnvironment.sslFipsRequired = sslFips;
        MQEnvironment.sslCipherSuite = sslCipherSuite;
    } catch (Exception ex) {
        handleException(ex.getMessage());
    }
}

From source file:org.apache.synapse.transport.nhttp.HttpCoreNIOSSLListener.java

/**
 * Create the SSLContext to be used by this listener
 * @param transportIn the Axis2 transport description
 * @return the SSLContext to be used//from   w  w w . j  a  v a 2s .  com
 */
protected SSLContext getSSLContext(TransportInDescription transportIn) throws AxisFault {

    KeyManager[] keymanagers = null;
    TrustManager[] trustManagers = null;

    Parameter keyParam = transportIn.getParameter("keystore");
    Parameter trustParam = transportIn.getParameter("truststore");

    if (keyParam != null) {
        OMElement ksEle = keyParam.getParameterElement().getFirstElement();
        String location = ksEle.getFirstChildWithName(new QName("Location")).getText();
        String type = ksEle.getFirstChildWithName(new QName("Type")).getText();
        String storePassword = ksEle.getFirstChildWithName(new QName("Password")).getText();
        String keyPassword = ksEle.getFirstChildWithName(new QName("KeyPassword")).getText();

        FileInputStream fis = null;
        try {
            KeyStore keyStore = KeyStore.getInstance(type);
            fis = new FileInputStream(location);
            log.info("Loading Identity Keystore from : " + location);

            keyStore.load(fis, storePassword.toCharArray());
            KeyManagerFactory kmfactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmfactory.init(keyStore, keyPassword.toCharArray());
            keymanagers = kmfactory.getKeyManagers();

        } catch (GeneralSecurityException gse) {
            log.error("Error loading Key store : " + location, gse);
            throw new AxisFault("Error loading Key store : " + location, gse);
        } catch (IOException ioe) {
            log.error("Error opening Key store : " + location, ioe);
            throw new AxisFault("Error opening Key store : " + location, ioe);
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException ignore) {
                }
            }
        }
    }

    if (trustParam != null) {
        OMElement tsEle = trustParam.getParameterElement().getFirstElement();
        String location = tsEle.getFirstChildWithName(new QName("Location")).getText();
        String type = tsEle.getFirstChildWithName(new QName("Type")).getText();
        String storePassword = tsEle.getFirstChildWithName(new QName("Password")).getText();

        FileInputStream fis = null;
        try {
            KeyStore trustStore = KeyStore.getInstance(type);
            fis = new FileInputStream(location);
            log.info("Loading Trust Keystore from : " + location);

            trustStore.load(fis, storePassword.toCharArray());
            TrustManagerFactory trustManagerfactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerfactory.init(trustStore);
            trustManagers = trustManagerfactory.getTrustManagers();

        } catch (GeneralSecurityException gse) {
            log.error("Error loading Key store : " + location, gse);
            throw new AxisFault("Error loading Key store : " + location, gse);
        } catch (IOException ioe) {
            log.error("Error opening Key store : " + location, ioe);
            throw new AxisFault("Error opening Key store : " + location, ioe);
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException ignore) {
                }
            }
        }
    }

    try {
        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(keymanagers, trustManagers, null);
        return sslcontext;

    } catch (GeneralSecurityException gse) {
        log.error("Unable to create SSL context with the given configuration", gse);
        throw new AxisFault("Unable to create SSL context with the given configuration", gse);
    }
}

From source file:org.apache.hadoop.security.ssl.ReloadingX509KeyManager.java

private X509ExtendedKeyManager loadKeyManager() throws GeneralSecurityException, IOException {
    KeyStore keyStore = KeyStore.getInstance(type);
    String keyStorePass;/*from w  w  w .  jav a  2s .c  o m*/
    String keyPass;
    if (passwordFileLocation != null) {
        keyStorePass = FileUtils.readFileToString(passwordFileLocation);
        keyPass = keyStorePass;
    } else {
        keyStorePass = keystorePassword;
        keyPass = keyPassword;
    }
    try (FileInputStream in = new FileInputStream(location)) {
        keyStore.load(in, keyStorePass.toCharArray());
        lastLoadedTimestamp = location.lastModified();
        LOG.debug("Loaded keystore file: " + location);
    }

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(SSLFactory.SSLCERTIFICATE);
    kmf.init(keyStore, keyPass.toCharArray());
    X509ExtendedKeyManager keyManager = null;
    KeyManager[] keyManagers = kmf.getKeyManagers();
    for (KeyManager km : keyManagers) {
        if (km instanceof X509ExtendedKeyManager) {
            keyManager = (X509ExtendedKeyManager) km;
            break;
        }
    }

    return keyManager;
}

From source file:davmail.util.ClientCertificateTest.java

public void testClientSocket() throws NoSuchAlgorithmException, KeyStoreException, IOException,
        CertificateException, KeyManagementException, UnrecoverableKeyException {

    //System.setProperty("javax.net.ssl.trustStoreProvider", "SunMSCAPI");
    //System.setProperty("javax.net.ssl.trustStoreType", "Windows-ROOT");
    System.setProperty("javax.net.ssl.trustStore", "cacerts");
    System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
    System.setProperty("javax.net.ssl.trustStoreType", "JKS");

    String algorithm = KeyManagerFactory.getDefaultAlgorithm();
    if ("SunX509".equals(algorithm)) {
        algorithm = "NewSunX509";
    } else if ("IbmX509".equals(algorithm)) {
        algorithm = "NewIbmX509";
    }// w  ww  .  j  a v a  2s .  c  o  m

    Provider sunMSCAPI = new sun.security.mscapi.SunMSCAPI();
    //Security.insertProviderAt(sunMSCAPI, 1);
    KeyStore keyStore = KeyStore.getInstance("Windows-MY", sunMSCAPI);
    keyStore.load(null, null);

    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(algorithm);
    keyManagerFactory.init(keyStore, null);

    // Get a list of key managers
    KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();

    // Walk through the key managers and replace all X509 Key Managers with
    // a specialized wrapped DavMail X509 Key Manager
    for (int i = 0; i < keyManagers.length; i++) {
        KeyManager keyManager = keyManagers[i];
        if (keyManager instanceof X509KeyManager) {
            keyManagers[i] = new DavMailX509KeyManager((X509KeyManager) keyManager);
        }
    }

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(keyManagers, null, null);
    SSLSocketFactory sockFactory = sslContext.getSocketFactory();
    SSLSocket sslSock = (SSLSocket) sockFactory.createSocket("localhost", 443);
    sslSock.startHandshake();

}

From source file:com.grendelscan.proxy.ssl.TunneledSSLConnection.java

private SSLSocketFactory initializeSSLFactory() throws GeneralSecurityException, IOException {
    LOGGER.trace("Initializing SSL for tunnel");
    if (ca == null) {
        LOGGER.trace("Getting the static CA");
        ca = CertificateAuthority.getCertificateAuthority();
    }//  w ww . j  a  v  a2  s . c  o m

    KeyManagerFactory kmfactory;
    KeyStore keystore = ca.getKeyStore(destinationHostname);

    kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmfactory.init(keystore, ca.getKeyPassword());
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(kmfactory.getKeyManagers(), null, null);
    return sslContext.getSocketFactory();
}

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

private KeyManagerFactory getKeyManagerFactory(final KeyStore keystore, final String password)
        throws KeyStoreException {
    try {/*from  w  w w . j  a  v  a  2 s .c o  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. 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.springframework.integration.x.http.NettyHttpInboundChannelAdapter.java

private SSLContext initializeSSLContext() throws Exception {
    Assert.state(this.sslPropertiesLocation != null, "KeyStore and pass phrase properties file required");
    Properties sslProperties = new Properties();
    sslProperties.load(this.sslPropertiesLocation.getInputStream());
    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    String keyStoreName = sslProperties.getProperty("keyStore");
    Assert.state(StringUtils.hasText(keyStoreName), "keyStore property cannot be null");
    String keyStorePassPhrase = sslProperties.getProperty("keyStore.passPhrase");
    Assert.state(StringUtils.hasText(keyStorePassPhrase), "keyStore.passPhrase property cannot be null");
    Resource keyStore = resolver.getResource(keyStoreName);
    SSLContext sslContext = SSLContext.getInstance("TLS");
    KeyStore ks = KeyStore.getInstance("PKCS12");
    ks.load(keyStore.getInputStream(), keyStorePassPhrase.toCharArray());
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
    kmf.init(ks, keyStorePassPhrase.toCharArray());
    sslContext.init(kmf.getKeyManagers(), null, null);
    return sslContext;
}

From source file:com.amazon.alexa.avs.auth.companionservice.CompanionServiceClient.java

/**
 * Loads the CA certificate into an in-memory keystore and creates an {@link SSLSocketFactory}.
 *
 * @return SSLSocketFactory//from w ww  .j  a  va 2  s  . c  om
 */
public SSLSocketFactory getPinnedSSLSocketFactory() {
    InputStream caCertInputStream = null;
    InputStream clientKeyPair = null;
    try {
        // Load the CA certificate into memory
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        caCertInputStream = new FileInputStream(deviceConfig.getCompanionServiceInfo().getSslCaCert());
        Certificate caCert = cf.generateCertificate(caCertInputStream);

        // Load the CA certificate into the trusted KeyStore
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        trustStore.setCertificateEntry("myca", caCert);

        // Create a TrustManagerFactory with the trusted KeyStore
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);

        // Load the client certificate and private key into another KeyStore
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        clientKeyPair = new FileInputStream(deviceConfig.getCompanionServiceInfo().getSslClientKeyStore());
        keyStore.load(clientKeyPair,
                deviceConfig.getCompanionServiceInfo().getSslClientKeyStorePassphrase().toCharArray());

        // Create a TrustManagerFactory with the client key pair KeyStore
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore,
                deviceConfig.getCompanionServiceInfo().getSslClientKeyStorePassphrase().toCharArray());

        // Initialize the SSLContext and return an SSLSocketFactory;
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

        return sc.getSocketFactory();
    } catch (CertificateException | KeyStoreException | UnrecoverableKeyException | NoSuchAlgorithmException
            | IOException | KeyManagementException e) {
        throw new RuntimeException("The KeyStore for contacting the Companion Service could not be loaded.", e);
    } finally {
        IOUtils.closeQuietly(caCertInputStream);
        IOUtils.closeQuietly(clientKeyPair);
    }
}

From source file:com.jive.myco.seyren.core.util.graphite.GraphiteHttpClient.java

private HttpClientConnectionManager createConnectionManager() {
    PoolingHttpClientConnectionManager manager;
    if ("https".equals(graphiteScheme) && !StringUtils.isEmpty(graphiteKeyStore)
            && !StringUtils.isEmpty(graphiteKeyStorePassword) && !StringUtils.isEmpty(graphiteTrustStore)) {
        try {/*from w  w w. j a va 2s .  c o m*/
            KeyStore keyStore = loadKeyStore(graphiteKeyStore, graphiteKeyStorePassword);
            KeyStore trustStore = loadKeyStore(graphiteTrustStore, null);

            KeyManagerFactory keyManagerFactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyManagerFactory.init(keyStore, graphiteKeyStorePassword.toCharArray());
            KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();

            TrustManagerFactory trustManagerFactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(trustStore);
            TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();

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

            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);

            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                    .<ConnectionSocketFactory>create().register("https", sslsf).build();

            manager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        } catch (Exception e) {
            LOGGER.warn("A problem occurred when building SSLConnectionSocketFactory", e);
            throw new RuntimeException("Error while building SSLConnectionSocketFactory", e);
        }
    } else {
        manager = new PoolingHttpClientConnectionManager();
    }

    manager.setDefaultMaxPerRoute(MAX_CONNECTIONS_PER_ROUTE);
    return manager;
}

From source file:org.apache.hadoop.security.ssl.FileBasedKeyStoresFactory.java

private void createKeyManagers(SSLFactory.Mode mode) throws IOException, GeneralSecurityException {
    boolean requireClientCert = conf.getBoolean(SSLFactory.SSL_REQUIRE_CLIENT_CERT_KEY,
            SSLFactory.DEFAULT_SSL_REQUIRE_CLIENT_CERT);

    String keystoreType = conf.get(resolvePropertyName(mode, SSL_KEYSTORE_TYPE_TPL_KEY), DEFAULT_KEYSTORE_TYPE);

    if (requireClientCert || mode == SSLFactory.Mode.SERVER) {
        String locationProperty = resolvePropertyName(mode, SSL_KEYSTORE_LOCATION_TPL_KEY);
        String keystoreLocation = conf.get(locationProperty, "");
        if (keystoreLocation.isEmpty()) {
            throw new GeneralSecurityException(
                    "The property '" + locationProperty + "' has not been set in the ssl configuration file.");
        }/* www . ja  v  a 2s .c o m*/
        String passwordProperty = resolvePropertyName(mode, SSL_KEYSTORE_PASSWORD_TPL_KEY);
        String keystorePassword = getPassword(conf, passwordProperty, "");
        if (keystorePassword.isEmpty()) {
            throw new GeneralSecurityException(
                    "The property '" + passwordProperty + "' has not been set in the ssl configuration file.");
        }
        String keyPasswordProperty = resolvePropertyName(mode, SSL_KEYSTORE_KEYPASSWORD_TPL_KEY);
        // Key password defaults to the same value as store password for
        // compatibility with legacy configurations that did not use a separate
        // configuration property for key password.
        String keystoreKeyPassword = getPassword(conf, keyPasswordProperty, keystorePassword);
        if (LOG.isDebugEnabled()) {
            LOG.debug(mode.toString() + " KeyStore: " + keystoreLocation);
        }

        long keyStoreReloadInterval = conf.getLong(
                resolvePropertyName(mode, SSL_KEYSTORE_RELOAD_INTERVAL_TPL_KEY),
                DEFAULT_SSL_KEYSTORE_RELOAD_INTERVAL);
        String timeUnitStr = conf.get(resolvePropertyName(mode, SSL_KEYSTORE_RELOAD_TIMEUNIT_TPL_KEY),
                DEFAULT_SSL_KEYSTORE_RELOAD_TIMEUNIT);
        TimeUnit reloadTimeUnit = TimeUnit.valueOf(timeUnitStr.toUpperCase());

        String passwordFileLocationProperty = resolvePropertyName(mode, SSL_PASSWORDFILE_LOCATION_TPL_KEY);
        String passwordFileLocation = conf.get(passwordFileLocationProperty, null);
        keyManager = new ReloadingX509KeyManager(keystoreType, keystoreLocation, keystorePassword,
                passwordFileLocation, keystoreKeyPassword, keyStoreReloadInterval, reloadTimeUnit);

        keyManager.init();
        if (LOG.isDebugEnabled()) {
            LOG.debug(mode.toString() + " Loaded KeyStore: " + keystoreLocation);
        }
        keyManagers = new KeyManager[] { keyManager };
    } else {
        // Deal with it
        KeyStore keyStore = KeyStore.getInstance(keystoreType);
        keyStore.load(null, null);
        KeyManagerFactory keyMgrFactory = KeyManagerFactory.getInstance(SSLFactory.SSLCERTIFICATE);
        keyMgrFactory.init(keyStore, null);
        keyManagers = keyMgrFactory.getKeyManagers();
    }
}