Example usage for javax.net.ssl KeyManagerFactory getInstance

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

Introduction

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

Prototype

public static final KeyManagerFactory getInstance(String algorithm) throws NoSuchAlgorithmException 

Source Link

Document

Returns a KeyManagerFactory object that acts as a factory for key managers.

Usage

From source file:com.sonatype.nexus.ssl.plugin.internal.TrustStoreImpl.java

private static KeyManager[] getSystemKeyManagers() throws Exception {
    KeyManagerFactory keyManagerFactory;

    String keyAlgorithm = System.getProperty("ssl.KeyManagerFactory.algorithm");
    if (keyAlgorithm == null) {
        keyAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
    }// w ww  .  java  2  s.com
    String keyStoreType = System.getProperty("javax.net.ssl.keyStoreType");
    if (keyStoreType == null) {
        keyStoreType = KeyStore.getDefaultType();
    }
    if ("none".equalsIgnoreCase(keyStoreType)) {
        keyManagerFactory = KeyManagerFactory.getInstance(keyAlgorithm);
    } else {
        final String keyStoreFileName = System.getProperty("javax.net.ssl.keyStore");
        if (keyStoreFileName != null) {
            File keyStoreFile = new File(keyStoreFileName);
            keyManagerFactory = KeyManagerFactory.getInstance(keyAlgorithm);
            String keyStoreProvider = System.getProperty("javax.net.ssl.keyStoreProvider");
            KeyStore keyStore;
            if (keyStoreProvider != null) {
                keyStore = KeyStore.getInstance(keyStoreType, keyStoreProvider);
            } else {
                keyStore = KeyStore.getInstance(keyStoreType);
            }
            String password = System.getProperty("javax.net.ssl.keyStorePassword");
            try (FileInputStream in = new FileInputStream(keyStoreFile)) {
                keyStore.load(in, password != null ? password.toCharArray() : null);
            }
            keyManagerFactory.init(keyStore, password != null ? password.toCharArray() : null);
        } else {
            return null;
        }
    }

    return keyManagerFactory.getKeyManagers();
}

From source file:org.globus.gsi.jsse.SSLConfigurator.java

private KeyManager[] loadKeyManagers() throws GlobusSSLConfigurationException {
    try {/*from  w  ww.  j a v  a  2s.c om*/
        KeyStore inputKeyStore;
        if (this.credentialStore == null) {
            if (this.credentialStoreLocation == null)
                return null;

            inputKeyStore = GlobusSSLHelper.findCredentialStore(this.provider, this.credentialStoreType,
                    this.credentialStoreLocation, this.credentialStorePassword);
        } else {
            inputKeyStore = this.credentialStore;
        }
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(sslKeyManagerFactoryAlgorithm);
        keyManagerFactory.init(inputKeyStore,
                credentialStorePassword == null ? null : credentialStorePassword.toCharArray());
        return keyManagerFactory.getKeyManagers();
    } catch (KeyStoreException e) {
        throw new GlobusSSLConfigurationException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new GlobusSSLConfigurationException(e);
    } catch (UnrecoverableKeyException e) {
        throw new GlobusSSLConfigurationException(e);
    }
}

From source file:org.wso2.carbon.inbound.endpoint.protocol.rabbitmq.RabbitMQConnectionFactory.java

/**
 * Initialize connection factory/*from   w w w .j  ava  2s.c o  m*/
 */
public void initConnectionFactory() {
    connectionFactory = new ConnectionFactory();
    String hostName = parameters.get(RabbitMQConstants.SERVER_HOST_NAME);
    String portValue = parameters.get(RabbitMQConstants.SERVER_PORT);
    String serverRetryIntervalS = parameters.get(RabbitMQConstants.SERVER_RETRY_INTERVAL);
    String retryIntervalS = parameters.get(RabbitMQConstants.RETRY_INTERVAL);
    String retryCountS = parameters.get(RabbitMQConstants.RETRY_COUNT);
    String heartbeat = parameters.get(RabbitMQConstants.HEARTBEAT);
    String connectionTimeout = parameters.get(RabbitMQConstants.CONNECTION_TIMEOUT);
    String sslEnabledS = parameters.get(RabbitMQConstants.SSL_ENABLED);
    String userName = parameters.get(RabbitMQConstants.SERVER_USER_NAME);
    String password = parameters.get(RabbitMQConstants.SERVER_PASSWORD);
    String virtualHost = parameters.get(RabbitMQConstants.SERVER_VIRTUAL_HOST);

    if (!StringUtils.isEmpty(heartbeat)) {
        try {
            int heartbeatValue = Integer.parseInt(heartbeat);
            connectionFactory.setRequestedHeartbeat(heartbeatValue);
        } catch (NumberFormatException e) {
            //proceeding with rabbitmq default value
            log.warn("Number format error in reading heartbeat value. Proceeding with default");
        }
    }
    if (!StringUtils.isEmpty(connectionTimeout)) {
        try {
            int connectionTimeoutValue = Integer.parseInt(connectionTimeout);
            connectionFactory.setConnectionTimeout(connectionTimeoutValue);
        } catch (NumberFormatException e) {
            //proceeding with rabbitmq default value
            log.warn("Number format error in reading connection timeout value. Proceeding with default");
        }
    }

    if (!StringUtils.isEmpty(sslEnabledS)) {
        try {
            boolean sslEnabled = Boolean.parseBoolean(sslEnabledS);
            if (sslEnabled) {
                String keyStoreLocation = parameters.get(RabbitMQConstants.SSL_KEYSTORE_LOCATION);
                String keyStoreType = parameters.get(RabbitMQConstants.SSL_KEYSTORE_TYPE);
                String keyStorePassword = parameters.get(RabbitMQConstants.SSL_KEYSTORE_PASSWORD);
                String trustStoreLocation = parameters.get(RabbitMQConstants.SSL_TRUSTSTORE_LOCATION);
                String trustStoreType = parameters.get(RabbitMQConstants.SSL_TRUSTSTORE_TYPE);
                String trustStorePassword = parameters.get(RabbitMQConstants.SSL_TRUSTSTORE_PASSWORD);
                String sslVersion = parameters.get(RabbitMQConstants.SSL_VERSION);

                if (StringUtils.isEmpty(keyStoreLocation) || StringUtils.isEmpty(keyStoreType)
                        || StringUtils.isEmpty(keyStorePassword) || StringUtils.isEmpty(trustStoreLocation)
                        || StringUtils.isEmpty(trustStoreType) || StringUtils.isEmpty(trustStorePassword)) {
                    log.warn(
                            "Truststore and keystore information is not provided correctly. Proceeding with default SSL configuration");
                    connectionFactory.useSslProtocol();
                } else {
                    char[] keyPassphrase = keyStorePassword.toCharArray();
                    KeyStore ks = KeyStore.getInstance(keyStoreType);
                    ks.load(new FileInputStream(keyStoreLocation), keyPassphrase);

                    KeyManagerFactory kmf = KeyManagerFactory
                            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
                    kmf.init(ks, keyPassphrase);

                    char[] trustPassphrase = trustStorePassword.toCharArray();
                    KeyStore tks = KeyStore.getInstance(trustStoreType);
                    tks.load(new FileInputStream(trustStoreLocation), trustPassphrase);

                    TrustManagerFactory tmf = TrustManagerFactory
                            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
                    tmf.init(tks);

                    SSLContext c = SSLContext.getInstance(sslVersion);
                    c.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

                    connectionFactory.useSslProtocol(c);
                }
            }
        } catch (Exception e) {
            log.warn("Format error in SSL enabled value. Proceeding without enabling SSL", e);
        }
    }

    if (!StringUtils.isEmpty(retryCountS)) {
        try {
            retryCount = Integer.parseInt(retryCountS);
        } catch (NumberFormatException e) {
            log.warn("Number format error in reading retry count value. Proceeding with default value (3)", e);
        }
    }

    if (!StringUtils.isEmpty(hostName)) {
        connectionFactory.setHost(hostName);
    } else {
        handleException("Host name is not defined");
    }

    try {
        int port = Integer.parseInt(portValue);
        if (port > 0) {
            connectionFactory.setPort(port);
        }
    } catch (NumberFormatException e) {
        handleException("Number format error in port number", e);
    }

    if (!StringUtils.isEmpty(userName)) {
        connectionFactory.setUsername(userName);
    }

    if (!StringUtils.isEmpty(password)) {
        connectionFactory.setPassword(password);
    }

    if (!StringUtils.isEmpty(virtualHost)) {
        connectionFactory.setVirtualHost(virtualHost);
    }

    if (!StringUtils.isEmpty(retryIntervalS)) {
        try {
            retryInterval = Integer.parseInt(retryIntervalS);
        } catch (NumberFormatException e) {
            log.warn(
                    "Number format error in reading retry interval value. Proceeding with default value (30000ms)",
                    e);
        }
    }

    if (!StringUtils.isEmpty(serverRetryIntervalS)) {
        try {
            int serverRetryInterval = Integer.parseInt(serverRetryIntervalS);
            connectionFactory.setNetworkRecoveryInterval(serverRetryInterval);
        } catch (NumberFormatException e) {
            log.warn(
                    "Number format error in reading server retry interval value. Proceeding with default value",
                    e);
        }
    }

    connectionFactory.setAutomaticRecoveryEnabled(true);
    connectionFactory.setTopologyRecoveryEnabled(false);
}

From source file:org.apache.commons.httpclient.contrib.ssl.AuthSSLProtocolSocketFactory.java

private static KeyManager[] createKeyManagers(final KeyStore keystore, final String password)
        throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {
    if (keystore == null) {
        throw new IllegalArgumentException("Keystore may not be null");
    }/*from   w  w w .  j  av a  2s.  c  om*/
    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:org.jboss.aerogear.windows.mpns.MpnsServiceBuilder.java

/**
 * Returns a fully initialized instance of {@link MpnsService},
 * according to the requested settings.//from  www .j  a  v a 2 s  . c  o  m
 *
 * @return  a new instance of MpnsService
 */
public MpnsService build() {
    checkInitialization();

    // Client Configuration
    HttpClient client;
    if (httpClient != null) {
        client = httpClient;
    } else if (pooledMax == 1) {
        client = new DefaultHttpClient();
    } else {
        client = new DefaultHttpClient(Utilities.poolManager(pooledMax));
    }

    if (proxy != null) {
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }

    if (securityInfo != null) {
        try {
            KeyStore keyStore;
            if (securityInfo.getProvider() == null) {
                keyStore = KeyStore.getInstance(securityInfo.getName());
            } else {
                keyStore = KeyStore.getInstance(securityInfo.getName(), securityInfo.getProvider());
            }
            keyStore.load(new ByteArrayInputStream(securityInfo.getCert()),
                    securityInfo.getPassword().toCharArray());

            KeyManagerFactory kmfactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmfactory.init(keyStore, securityInfo.getPassword().toCharArray());
            KeyManager[] km = kmfactory.getKeyManagers();

            // create SSL socket factory
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(km, null, null);
            org.apache.http.conn.ssl.SSLSocketFactory sslSocketFactory = new org.apache.http.conn.ssl.SSLSocketFactory(
                    sslContext);

            Scheme https = new Scheme("https", 443, sslSocketFactory);
            client.getConnectionManager().getSchemeRegistry().register(https);
        } catch (Exception e) {
            throw new IllegalArgumentException(e);
        }
    }

    if (timeout > 0) {
        HttpParams params = client.getParams();
        HttpConnectionParams.setConnectionTimeout(params, timeout);
        HttpConnectionParams.setSoTimeout(params, timeout);
    }

    // Configure service
    AbstractMpnsService service;
    if (pooledMax == 1) {
        service = new MpnsServiceImpl(client, delegate);
    } else {
        service = new MpnsPooledService(client, executor, delegate);
    }

    if (isQueued) {
        service = new MpnsQueuedService(service);
    }

    service.start();
    return service;
}

From source file:com.app.mvc.http.ext.AuthSSLProtocolSocketFactory.java

private static KeyManager[] createKeyManagers(final KeyStore keystore, final String password)
        throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {
    if (keystore == null) {
        throw new IllegalArgumentException("Keystore may not be null");
    }//from   www .ja v  a 2s  .  c o m
    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.stargame.ad.util.http.ssl.AuthSSLProtocolSocketFactory.java

private static KeyManager[] createKeyManagers(final KeyStore keystore, final String password)
        throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {
    if (keystore == null) {
        throw new IllegalArgumentException("Keystore may not be null");
    }//from   w  w  w  . j a  v  a  2s  .com
    LogUtil.d(AuthSSLProtocolSocketFactory.class, "Initializing key manager");
    KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmfactory.init(keystore, password != null ? password.toCharArray() : null);
    return kmfactory.getKeyManagers();
}

From source file:cn.org.eshow.framwork.http.ssl.AuthSSLProtocolSocketFactory.java

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

From source file:org.apache.activemq.ActiveMQSslConnectionFactoryTest.java

public static KeyManager[] getKeyManager() throws Exception {
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    KeyStore ks = KeyStore.getInstance(ActiveMQSslConnectionFactoryTest.KEYSTORE_TYPE);
    KeyManager[] keystoreManagers = null;

    byte[] sslCert = loadClientCredential(ActiveMQSslConnectionFactoryTest.SERVER_KEYSTORE);

    if (sslCert != null && sslCert.length > 0) {
        ByteArrayInputStream bin = new ByteArrayInputStream(sslCert);
        ks.load(bin, ActiveMQSslConnectionFactoryTest.PASSWORD.toCharArray());
        kmf.init(ks, ActiveMQSslConnectionFactoryTest.PASSWORD.toCharArray());
        keystoreManagers = kmf.getKeyManagers();
    }//from   w  w  w.java  2s.co m
    return keystoreManagers;
}

From source file:opendap.dap.http.EasySSLProtocolSocketFactory.java

private SSLContext createSSLContext() throws HTTPException {
    try {/*from ww w. j a v  a 2s .  co  m*/
        KeyManager[] keymanagers = null;
        KeyStore keystore = null;
        KeyStore truststore = null;
        TrustManager[] trustmanagers = null;

        String keypassword = getpassword("key");
        String keypath = getstorepath("key");
        String trustpassword = getpassword("trust");
        String trustpath = getstorepath("trust");

        keystore = buildstore(keypath, keypassword, "key");
        if (keystore != null) {
            KeyManagerFactory kmfactory = KeyManagerFactory.getInstance("SunX509");
            kmfactory.init(keystore, keypassword.toCharArray());
            keymanagers = kmfactory.getKeyManagers();
        }

        truststore = buildstore(trustpath, trustpassword, "trust");
        if (truststore != null) {
            //TrustManagerFactory trfactory = TrustManagerFactory.getInstance("SunX509");
            //trfactory.init(truststore, trustpassword.toCharArray());
            //trustmanagers = trfactory.getTrustManagers();
            trustmanagers = new TrustManager[] { new EasyX509TrustManager(truststore) };
        }
        SSLContext sslcontext = SSLContext.getInstance("SSL");
        sslcontext.init(keymanagers, trustmanagers, null);
        return sslcontext;

    } catch (NoSuchAlgorithmException e) {
        throw new HTTPException("Unsupported algorithm exception: " + e.getMessage());
    } catch (KeyStoreException e) {
        throw new HTTPException("Keystore exception: " + e.getMessage());
    } catch (GeneralSecurityException e) {
        throw new HTTPException("Key management exception: " + e.getMessage());
    } catch (IOException e) {
        throw new HTTPException("I/O error reading keystore/truststore file: " + e.getMessage());
    }
}