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:immf.MyWiser.java

private SSLSocketFactory createSslSocketFactory(String keystoreFile, String keyType, String keypasswd) {
    InputStream keyis = null;// w w  w.ja v  a2s . c o  m
    try {
        keyis = new FileInputStream(keystoreFile);
        KeyStore keyStore = KeyStore.getInstance(keyType);
        keyStore.load(keyis, keypasswd.toCharArray());

        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(keyStore, keypasswd.toCharArray());

        SSLContext context = SSLContext.getInstance("TLS");

        context.init(kmf.getKeyManagers(), null, new SecureRandom());
        return context.getSocketFactory();
    } catch (Exception e) {
        e.printStackTrace();
        return (SSLSocketFactory) SSLSocketFactory.getDefault();
    } finally {
        try {
            keyis.close();
        } catch (Exception e) {
        }
    }
}

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 .  ja v a 2  s.  co  m
 */
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.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.");
        }/*from   w ww. ja v a2s.  co 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();
    }
}

From source file:org.wso2.msf4j.conf.SSLClientContext.java

public SSLClientContext(File keyStore, String keyStorePassword) {

    try {// w  w w  . ja va 2 s .c o  m
        KeyManagerFactory kmf = null;
        if (keyStore != null && keyStorePassword != null) {
            KeyStore ks = getKeyStore(keyStore, keyStorePassword);
            kmf = KeyManagerFactory.getInstance("SunX509");
            kmf.init(ks, keyStorePassword.toCharArray());
        }
        clientContext = SSLContext.getInstance(protocol);
        clientContext.init(kmf == null ? null : kmf.getKeyManagers(), TrustManagerFactory.getTrustManagers(),
                null);
    } catch (Exception e) {
        throw new RuntimeException("Failed to initialize the client-side SSLContext", e);
    }
}

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.thesocialcoin.networking.SSL.EasySSLSocketFactory.java

private static SSLContext createEasySSLContext() throws IOException {
    try {//from w  w w .  j  a va 2 s .  c  om

        // Client should authenticate itself with the valid certificate to Server.
        InputStream clientStream = App.getAppContext().getResources()
                .openRawResource(R.raw.production_test_client);
        char[] password = "XXXXXXXXXXXXX".toCharArray();

        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        keyStore.load(clientStream, password);

        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, password);

        // Client should also add the CA certificate obtained from server and create TrustManager from it for the client to validate the
        // identity of the server.
        KeyStore trustStore = KeyStore.getInstance("BKS");
        InputStream instream = null;
        instream = App.getAppContext().getResources().openRawResource(R.raw.production_test_ca);

        try {
            trustStore.load(instream, "XXXXXXXX".toCharArray());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                instream.close();
            } catch (Exception ignore) {
            }
        }

        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init(trustStore);

        // Create an SSLContext that uses our TrustManager & Keystore
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(keyManagerFactory.getKeyManagers(), tmf.getTrustManagers(), null);

        return context;
    } catch (Exception e) {
        e.printStackTrace();
        throw new IOException(e.getMessage());
    }
}

From source file:org.kuali.mobility.push.factory.iOSFeedbackConnectionFactory.java

@Override
public SSLSocket makeObject() throws Exception {
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    keyStore.load(certPath.getInputStream(), certPassword.toCharArray());
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("sunx509");
    keyManagerFactory.init(keyStore, certPassword.toCharArray());
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("sunx509");
    trustManagerFactory.init(keyStore);//w  ww .j  av  a 2  s.c o m
    SSLContext sslCtx = SSLContext.getInstance("TLS");
    sslCtx.init(keyManagerFactory.getKeyManagers(), null, null);
    SSLSocketFactory sslSocketFactory = sslCtx.getSocketFactory();
    SSLSocket socket = (SSLSocket) sslSocketFactory.createSocket(host, port);
    socket.startHandshake();
    return socket;
}

From source file:org.kuali.mobility.push.factory.iOSConnectionFactory.java

@Override
public SSLSocket makeObject() throws Exception {
    SSLSocket socket = null;// w  ww.j a  v a 2  s. c  om
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    keyStore.load(certPath.getInputStream(), certPassword.toCharArray());
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("sunx509");
    keyManagerFactory.init(keyStore, certPassword.toCharArray());
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("sunx509");
    trustManagerFactory.init(keyStore);
    SSLContext sslCtx = SSLContext.getInstance("TLS");
    sslCtx.init(keyManagerFactory.getKeyManagers(), null, null);
    SSLSocketFactory sslSocketFactory = sslCtx.getSocketFactory();
    socket = (SSLSocket) sslSocketFactory.createSocket(host, port);
    socket.startHandshake();
    return socket;
}

From source file:com.eviware.soapui.impl.wsdl.support.http.SoapUISSLSocketFactory.java

@SuppressWarnings("deprecation")
public SoapUISSLSocketFactory(KeyStore keyStore, String keystorePassword)
        throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException {
    super(keyStore);

    // trust everyone!
    X509TrustManager tm = new X509TrustManager() {
        @Override//from   w w  w . ja  va 2s  . c  o  m
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkClientTrusted(X509Certificate[] certs, String authType) {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] certs, String authType) {
        }
    };

    if (keyStore != null) {
        KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmfactory.init(keyStore, keystorePassword != null ? keystorePassword.toCharArray() : null);
        KeyManager[] keymanagers = kmfactory.getKeyManagers();
        sslContext.init(keymanagers, new TrustManager[] { tm }, null);
    } else {
        sslContext.init(null, new TrustManager[] { tm }, null);
    }

    setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

}

From source file:com.ring.ytjojo.ssl.EasySSLSocketFactory.java

private static SSLContext createEasySSLContext() throws IOException {
    try {//from  w w  w. j  av  a  2  s .co m

        // Client should authenticate itself with the valid certificate to Server.
        InputStream clientStream = AppContext_.getInstance().getResources()
                .openRawResource(R.raw.production_test_client);
        char[] password = "XXXXXXXXXXXXX".toCharArray();

        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        keyStore.load(clientStream, password);

        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, password);

        // Client should also add the CA certificate obtained from server and create TrustManager from it for the client to validate the 
        // identity of the server.
        KeyStore trustStore = KeyStore.getInstance("BKS");
        InputStream instream = null;
        instream = AppContext_.getInstance().getResources().openRawResource(R.raw.production_test_ca);

        try {
            trustStore.load(instream, "XXXXXXXX".toCharArray());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                instream.close();
            } catch (Exception ignore) {
            }
        }

        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init(trustStore);

        // Create an SSLContext that uses our TrustManager & Keystore
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(keyManagerFactory.getKeyManagers(), tmf.getTrustManagers(), null);

        return context;
    } catch (Exception e) {
        e.printStackTrace();
        throw new IOException(e.getMessage());
    }
}