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:org.apache.synapse.transport.nhttp.HttpCoreNIOSSLSender.java

private SSLContext createSSLContext(OMElement keyStoreElt, OMElement trustStoreElt, boolean novalidatecert)
        throws AxisFault {

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

    if (keyStoreElt != null) {
        String location = keyStoreElt.getFirstChildWithName(new QName("Location")).getText();
        String type = keyStoreElt.getFirstChildWithName(new QName("Type")).getText();
        String storePassword = keyStoreElt.getFirstChildWithName(new QName("Password")).getText();
        String keyPassword = keyStoreElt.getFirstChildWithName(new QName("KeyPassword")).getText();

        FileInputStream fis = null;
        try {/*w  w  w .j  a v  a 2  s.c  o  m*/
            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 Keystore : " + location, gse);
            throw new AxisFault("Error loading Keystore : " + location, gse);
        } catch (IOException ioe) {
            log.error("Error opening Keystore : " + location, ioe);
            throw new AxisFault("Error opening Keystore : " + location, ioe);
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException ignore) {
                }
            }
        }
    }

    if (trustStoreElt != null) {
        if (novalidatecert) {
            log.warn("Ignoring novalidatecert parameter since a truststore has been specified");
        }

        String location = trustStoreElt.getFirstChildWithName(new QName("Location")).getText();
        String type = trustStoreElt.getFirstChildWithName(new QName("Type")).getText();
        String storePassword = trustStoreElt.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) {
                }
            }
        }
    } else if (novalidatecert) {
        log.warn("Server certificate validation (trust) has been disabled. " + "DO NOT USE IN PRODUCTION!");
        trustManagers = new TrustManager[] { new NoValidateCertTrustManager() };
    }

    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.globus.gsi.jsse.SSLConfigurator.java

private KeyManager[] loadKeyManagers() throws GlobusSSLConfigurationException {
    try {//w  w w.  j a  v a 2s . com
        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:net.roboconf.target.azure.internal.AzureIaasHandler.java

private SSLSocketFactory getSSLSocketFactory(String keyStoreName, String password)
        throws GeneralSecurityException, IOException {

    KeyStore ks = this.getKeyStore(keyStoreName, password);
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
    keyManagerFactory.init(ks, password.toCharArray());

    SSLContext context = SSLContext.getInstance("TLS");
    context.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom());

    return context.getSocketFactory();
}

From source file:com.myJava.file.driver.remote.ftp.SecuredSocketFactory.java

public SecuredSocketFactory(String protocol, String protection, boolean checkServerCertificate,
        boolean implicit, InputStream certificateInputStream, String certificatePassword, FTPSClient client) {
    Logger.defaultLogger().info("Initializing secured socket factory ...");
    acceptProtocol(protocol);/*from w ww  .  j a  va 2 s. co  m*/
    this.protocol = protocol;
    this.protection = protection;

    if (protection == null || (!protection.equals("C") && !protection.equals("P"))) {
        throw new IllegalArgumentException(
                "Illegal protection method : [" + protection + "]. Only \"C\" and \"P\" are accepted.");
    }

    this.implicit = implicit;
    this.client = client;

    TrustManager tm[] = null;
    KeyManager km[] = null;

    // Init the keyStore if needed
    if (certificateInputStream != null) {
        try {
            Logger.defaultLogger().info("Loading certificate ...");
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KEY_ALGORITHM);
            KeyStore ks = KeyStore.getInstance(KEY_TYPE);
            char[] pwdChars = (certificatePassword == null ? null : certificatePassword.toCharArray());
            ks.load(certificateInputStream, pwdChars);
            kmf.init(ks, pwdChars);
            km = kmf.getKeyManagers();
        } catch (Exception e) {
            Logger.defaultLogger().error(e);
        }
    }

    // Init the trustmanager if needed
    if (!checkServerCertificate) {
        Logger.defaultLogger().info("Disabling server identification ...");
        tm = NO_CHECK_TM;
    }

    try {
        sslContext = SSLContext.getInstance(protocol);
        sslContext.init(km, tm, null);
    } catch (NoSuchAlgorithmException e) {
        Logger.defaultLogger().error(e);
    } catch (KeyManagementException e) {
        Logger.defaultLogger().error(e);
    }
}

From source file:org.ejbca.core.protocol.ocsp.OCSPUnidClient.java

private SSLSocketFactory getSSLFactory() throws IOException, NoSuchAlgorithmException,
        UnrecoverableKeyException, KeyStoreException, CertificateException, KeyManagementException {

    final KeyManager km[];
    final TrustManager tm[];

    // Put the key and certs in the user keystore (if available)
    if (this.ks != null) {
        final KeyManagerFactory kmf;
        kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(this.ks, this.passphrase.toCharArray());
        km = kmf.getKeyManagers();
    } else {//from w  w w.jav a  2 s.  co  m
        km = null;
    }
    // Now make a truststore to verify the server
    if (this.certChain != null && this.certChain.length > 0) {
        final KeyStore trustks = KeyStore.getInstance("jks");
        trustks.load(null, "foo123".toCharArray());
        // add trusted CA cert
        trustks.setCertificateEntry("trusted", this.certChain[this.certChain.length - 1]);
        final TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
        tmf.init(trustks);
        tm = tmf.getTrustManagers();
    } else {
        tm = null;
    }
    if (km == null && tm == null) {
        return (SSLSocketFactory) SSLSocketFactory.getDefault();
    }
    final SSLContext ctx = SSLContext.getInstance("TLS");
    ctx.init(km, tm, null);

    return ctx.getSocketFactory();
}

From source file:org.apache.ranger.plugin.util.RangerRESTClient.java

private KeyManager[] getKeyManagers() {
    KeyManager[] kmList = null;/*from  w w  w . j a va2s . c om*/

    String keyStoreFilepwd = getCredential(mKeyStoreURL, mKeyStoreAlias);

    if (!StringUtil.isEmpty(mKeyStoreFile) && !StringUtil.isEmpty(keyStoreFilepwd)) {
        InputStream in = null;

        try {
            in = getFileInputStream(mKeyStoreFile);

            if (in != null) {
                KeyStore keyStore = KeyStore.getInstance(mKeyStoreType);

                keyStore.load(in, keyStoreFilepwd.toCharArray());

                KeyManagerFactory keyManagerFactory = KeyManagerFactory
                        .getInstance(RANGER_SSL_KEYMANAGER_ALGO_TYPE);

                keyManagerFactory.init(keyStore, keyStoreFilepwd.toCharArray());

                kmList = keyManagerFactory.getKeyManagers();
            } else {
                LOG.error("Unable to obtain keystore from file [" + mKeyStoreFile + "]");
            }
        } catch (KeyStoreException e) {
            LOG.error("Unable to obtain from KeyStore", e);
        } catch (NoSuchAlgorithmException e) {
            LOG.error("SSL algorithm is available in the environment", e);
        } catch (CertificateException e) {
            LOG.error("Unable to obtain the requested certification ", e);
        } catch (FileNotFoundException e) {
            LOG.error("Unable to find the necessary SSL Keystore and TrustStore Files", e);
        } catch (IOException e) {
            LOG.error("Unable to read the necessary SSL Keystore and TrustStore Files", e);
        } catch (UnrecoverableKeyException e) {
            LOG.error("Unable to recover the key from keystore", e);
        } finally {
            close(in, mKeyStoreFile);
        }
    }

    return kmList;
}

From source file:org.jboss.as.test.integration.logging.syslogserver.TLSSyslogServer.java

/**
 * Creates custom sslContext from keystore and truststore configured in
 *
 * @see org.productivity.java.syslog4j.server.impl.net.tcp.TCPNetSyslogServer#initialize()
 *///  ww w .j  av a2 s  .  c o m
@Override
public void initialize() throws SyslogRuntimeException {
    super.initialize();

    if (isBouncyCastleInstalled()) {
        removeBouncyCastle();
        addBouncyCastleOnShutdown = true;
    }

    final SSLTCPNetSyslogServerConfigIF config = (SSLTCPNetSyslogServerConfigIF) this.tcpNetSyslogServerConfig;

    try {
        final char[] keystorePwd = config.getKeyStorePassword().toCharArray();
        final KeyStore keystore = loadKeyStore(config.getKeyStore(), keystorePwd);
        final char[] truststorePassword = config.getTrustStorePassword().toCharArray();
        final KeyStore truststore = loadKeyStore(config.getTrustStore(), truststorePassword);

        final KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keystore, keystorePwd);

        final TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(truststore);

        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
    } catch (Exception e) {
        LOGGER.error("Exception occurred during SSLContext for TLS syslog server initialization", e);
        throw new SyslogRuntimeException(e);
    }
}

From source file:net.jradius.server.TCPListener.java

public void setConfiguration(ListenerConfigurationItem cfg, boolean noKeepAlive)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException,
        KeyManagementException, IOException {
    keepAlive = !noKeepAlive;/*from  w  w  w  .  ja  va 2 s  . c o m*/
    config = cfg;

    Map props = config.getProperties();

    String s = (String) props.get("port");
    if (s != null)
        port = new Integer(s).intValue();

    s = (String) props.get("backlog");
    if (s != null)
        backlog = new Integer(s).intValue();

    if (keepAlive) {
        s = (String) props.get("keepAlive");
        if (s != null)
            keepAlive = new Boolean(s).booleanValue();
    }

    String useSSL = (String) props.get("useSSL");
    String trustAll = (String) props.get("trustAll");

    if (requiresSSL || "true".equalsIgnoreCase(useSSL)) {
        KeyManager[] keyManagers = null;
        TrustManager[] trustManagers = null;

        String keyManager = (String) props.get("keyManager");

        if (keyManager != null && keyManager.length() > 0) {
            try {
                KeyManager manager = (KeyManager) Configuration.getBean(keyManager);
                keyManagers = new KeyManager[] { manager };
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            String keystore = (String) props.get("keyStore");
            String keystoreType = (String) props.get("keyStoreType");
            String keystorePassword = (String) props.get("keyStorePassword");
            String keyPassword = (String) props.get("keyPassword");

            if (keystore != null) {
                if (keystoreType == null)
                    keystoreType = "pkcs12";

                KeyStore ks = KeyStore.getInstance(keystoreType);
                ks.load(new FileInputStream(keystore),
                        keystorePassword == null ? null : keystorePassword.toCharArray());

                KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
                kmf.init(ks, keyPassword == null ? null : keyPassword.toCharArray());
                keyManagers = kmf.getKeyManagers();
            }
        }

        String trustManager = (String) props.get("trustManager");

        if (trustManager != null && trustManager.length() > 0) {
            try {
                TrustManager manager = (TrustManager) Configuration.getBean(trustManager);
                trustManagers = new TrustManager[] { manager };
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if ("true".equalsIgnoreCase(trustAll)) {
            trustManagers = new TrustManager[] { new X509TrustManager() {
                public void checkClientTrusted(X509Certificate[] chain, String authType) {

                }

                public void checkServerTrusted(X509Certificate[] chain, String authType) {

                }

                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }
            } };
        } else {
            String keystore = (String) props.get("caStore");
            String keystoreType = (String) props.get("caStoreType");
            String keystorePassword = (String) props.get("caStorePassword");

            if (keystore != null) {
                if (keystoreType == null)
                    keystoreType = "pkcs12";

                KeyStore caKeys = KeyStore.getInstance(keystoreType);
                caKeys.load(new FileInputStream(keystore),
                        keystorePassword == null ? null : keystorePassword.toCharArray());
                TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
                tmf.init(caKeys);
                trustManagers = tmf.getTrustManagers();
            }
        }

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

        ServerSocketFactory socketFactory = sslContext.getServerSocketFactory();
        SSLServerSocket sslServerSocket = (SSLServerSocket) socketFactory.createServerSocket(port, backlog);
        serverSocket = sslServerSocket;

        if (sslWantClientAuth)
            sslServerSocket.setWantClientAuth(true);

        if (sslNeedClientAuth)
            sslServerSocket.setNeedClientAuth(true);

        if (sslEnabledProtocols != null)
            sslServerSocket.setEnabledProtocols(sslEnabledProtocols);

        if (sslEnabledCiphers != null)
            sslServerSocket.setEnabledCipherSuites(sslEnabledCiphers);

        usingSSL = true;
    } else {
        serverSocket = new ServerSocket(port, backlog);
    }

    serverSocket.setReuseAddress(true);
    setActive(true);
}

From source file:com.appdynamics.monitors.azure.statsCollector.AzureServiceBusStatsCollector.java

private SSLSocketFactory getSSLSocketFactory(String keyStoreName, String password) {
    KeyStore ks = getKeyStore(keyStoreName, password);
    KeyManagerFactory keyManagerFactory = null;
    try {/* w  w  w  . j a v  a2 s . com*/
        keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
        keyManagerFactory.init(ks, password.toCharArray());
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom());
        return context.getSocketFactory();
    } catch (NoSuchAlgorithmException e) {
        logger.error(e.getMessage(), e);
        throw new RuntimeException(e.getMessage(), e);
    } catch (KeyStoreException e) {
        logger.error(e.getMessage(), e);
        throw new RuntimeException(e.getMessage(), e);
    } catch (UnrecoverableKeyException e) {
        logger.error(e.getMessage(), e);
        throw new RuntimeException(e.getMessage(), e);
    } catch (KeyManagementException e) {
        logger.error(e.getMessage(), e);
        throw new RuntimeException(e.getMessage(), e);
    }
}