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.wso2.carbon.esb.rabbitmq.message.store.jira.ESBJAVA4569RabbiMQSSLStoreWithClientCertValidationTest.java

/**
 * Helper method to retrieve queue message from rabbitMQ
 *
 * @return result/*from w ww .  j  a  va  2s .com*/
 * @throws Exception
 */
private static String consumeWithoutCertificate() throws Exception {
    String result = "";

    String basePath = TestConfigurationProvider.getResourceLocation()
            + "/artifacts/ESB/messageStore/rabbitMQ/SSL/";

    String truststoreLocation = basePath + "rabbitMQ/certs/client/rabbitstore";
    String keystoreLocation = basePath + "rabbitMQ/certs/client/keycert.p12";

    char[] keyPassphrase = "MySecretPassword".toCharArray();
    KeyStore ks = KeyStore.getInstance("PKCS12");
    ks.load(new FileInputStream(keystoreLocation), keyPassphrase);

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

    char[] trustPassphrase = "rabbitstore".toCharArray();
    KeyStore tks = KeyStore.getInstance("JKS");
    tks.load(new FileInputStream(truststoreLocation), trustPassphrase);

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

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

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    factory.setPort(5671);
    factory.useSslProtocol(c);

    Connection conn = factory.newConnection();
    Channel channel = conn.createChannel();

    GetResponse chResponse = channel.basicGet("WithClientCertQueue", true);
    if (chResponse != null) {
        byte[] body = chResponse.getBody();
        result = new String(body);
    }
    channel.close();
    conn.close();
    return result;
}

From source file:org.wso2.carbon.identity.authenticator.wikid.WiKIDAuthenticator.java

public static void setHttpsClientCert(String certificateFile, String certPassword) {
    try {/*from  w w w . ja  v a 2  s .  c o m*/
        if (certificateFile == null || !new File(certificateFile).exists()) {
            return;
        }
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        InputStream keyInput = new FileInputStream(certificateFile);
        keyStore.load(keyInput, certPassword.toCharArray());
        keyInput.close();
        keyManagerFactory.init(keyStore, certPassword.toCharArray());
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom());
        SSLContext.setDefault(context);
    } catch (KeyStoreException e) {
    } catch (NoSuchAlgorithmException e) {
    } catch (FileNotFoundException e) {
    } catch (IOException e) {
    } catch (CertificateException e) {
    } catch (UnrecoverableKeyException e) {
    } catch (KeyManagementException e) {
    }
}

From source file:learn.encryption.ssl.SSLContext_Https.java

/**
 * @description javaSSLContext/* w  w w . j a v a2  s . c o m*/
 * @description https?, SSLContext (NoHttp?SecureRandombug)
 * @description client.ks?server
 * @description ??
 * @description ????getSSLContext2()
 */
//@SuppressLint("TrulyRandom")
public static SSLContext getSSLContext() {
    SSLContext sslContext = null;
    try {
        sslContext = SSLContext.getInstance("TLS");
        // ??, ??assets
        InputStream inputStream = new FileInputStream(new File("D:\\tomcatcert\\server.ks"));
        //App.getInstance().getAssets().open("srca.cer");

        // ??
        CertificateFactory cerFactory = CertificateFactory.getInstance("X.509");

        // ?KeyStore
        KeyStore keyStore = KeyStore.getInstance("jks");
        keyStore.load(inputStream, "123456".toCharArray());
        //Certificate cer = cerFactory.generateCertificate(inputStream);
        Certificate cer = keyStore.getCertificate("clientKey");
        keyStore.setCertificateEntry("trust", cer);

        // KeyStorekeyManagerFactory
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, "123456".toCharArray());

        // KeyStoreTrustManagerFactory
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);

        // ?SSLContext
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(),
                new SecureRandom());
    } catch (Exception e) {
        e.printStackTrace();
    }

    return sslContext;
}

From source file:org.araqne.pkg.HttpWagon.java

public static InputStream openDownloadStream(URL url, TrustManagerFactory tmf, KeyManagerFactory kmf)
        throws KeyManagementException, IOException {
    SSLContext ctx = null;/*w w w. ja va 2 s  . c  o  m*/
    try {
        ctx = SSLContext.getInstance("SSL");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }

    TrustManager[] trustManagers = null;
    KeyManager[] keyManagers = null;
    if (tmf != null)
        trustManagers = tmf.getTrustManagers();
    if (kmf != null)
        keyManagers = kmf.getKeyManagers();

    ctx.init(keyManagers, trustManagers, new SecureRandom());

    HttpsSocketFactory h = new HttpsSocketFactory(kmf, tmf);
    Protocol https = new Protocol("https", (ProtocolSocketFactory) h, 443);
    Protocol.registerProtocol("https", https);

    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(url.toString());
    client.executeMethod(method);
    return method.getResponseBodyAsStream();
}

From source file:org.apache.hadoop.hdfsproxy.ProxyUtil.java

private static void setupSslProps(Configuration conf) throws IOException {
    FileInputStream fis = null;/*from   www.  jav  a 2  s  .  c om*/
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        KeyManager[] kms = null;
        TrustManager[] tms = null;
        if (conf.get("ssl.client.keystore.location") != null) {
            // initialize default key manager with keystore file and pass
            KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
            KeyStore ks = KeyStore.getInstance(conf.get("ssl.client.keystore.type", "JKS"));
            char[] ksPass = conf.get("ssl.client.keystore.password", "changeit").toCharArray();
            fis = new FileInputStream(conf.get("ssl.client.keystore.location", "keystore.jks"));
            ks.load(fis, ksPass);
            kmf.init(ks, conf.get("ssl.client.keystore.keypassword", "changeit").toCharArray());
            kms = kmf.getKeyManagers();
            fis.close();
            fis = null;
        }
        // initialize default trust manager with keystore file and pass
        if (conf.getBoolean("ssl.client.do.not.authenticate.server", false)) {
            // by pass trustmanager validation
            tms = new DummyTrustManager[] { new DummyTrustManager() };
        } else {
            TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
            KeyStore ts = KeyStore.getInstance(conf.get("ssl.client.truststore.type", "JKS"));
            char[] tsPass = conf.get("ssl.client.truststore.password", "changeit").toCharArray();
            fis = new FileInputStream(conf.get("ssl.client.truststore.location", "truststore.jks"));
            ts.load(fis, tsPass);
            tmf.init(ts);
            tms = tmf.getTrustManagers();
        }
        sc.init(kms, tms, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
        throw new IOException("Could not initialize SSLContext", e);
    } finally {
        if (fis != null) {
            fis.close();
        }
    }
}

From source file:com.gamesalutes.utils.EncryptUtils.java

/**
 * Creates an <code>SSLContext</code> that uses the specified trusted certificates.
 * //from ww  w .  j  av  a2  s  .  com
 * @param protocol the {@link TransportSecurityProtocol} to use for the context
 * @param trustedCerts certificates to import into the <code>SSLContext</code> or <code>null</code>
 *         to accept all issuers
 * @param privateKey the client key to authenticate the client with the server
 * @return the created <code>SSLContext</code>
 * @throws Exception if error occurs during the process of creating the context
 */
public static SSLContext createSSLContext(TransportSecurityProtocol protocol, PrivateKey privateKey,
        java.security.cert.X509Certificate... trustedCerts) throws Exception {
    if (trustedCerts != null && trustedCerts.length == 0)
        throw new IllegalArgumentException("trustedCerts is empty");

    X509TrustManager defaultManager = null;
    KeyManager[] keyManagers = null;
    KeyStore keyStore = null;

    if (privateKey != null || trustedCerts != null) {
        // create a new key store instance that will install the certificates
        // and/or the private keys
        keyStore = KeyStore.getInstance(JKS_TYPE);
        keyStore.load(null, null);
    }

    // import the certs
    if (trustedCerts != null) {
        // set up the key manager for the certificates
        javax.net.ssl.TrustManagerFactory trustFact = javax.net.ssl.TrustManagerFactory
                .getInstance(KEY_MANAGEMENT_ALG_SUN_X509);

        // install the certificates in the key store and give them a unique alias
        int imported = 0;
        for (java.security.cert.X509Certificate cert : trustedCerts) {
            if (cert != null)
                keyStore.setCertificateEntry("cert" + ++imported, cert);
        }
        if (imported == 0)
            throw new IllegalArgumentException("no non-null certs in trustedCerts");
        // add the certs to the trust factory
        trustFact.init(keyStore);

        // get a default trust manager
        TrustManager[] tms = trustFact.getTrustManagers();
        if (tms != null && tms.length >= 1)
            defaultManager = (X509TrustManager) tms[0];
    }

    // import the private key
    if (privateKey != null) {
        keyStore.setKeyEntry("client", privateKey, null, null);
        KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(privateKey.getAlgorithm());

        kmfactory.init(keyStore, null);
        keyManagers = kmfactory.getKeyManagers();
    }
    //create the SSL context based on these parameters
    SSLContext sslContext = SSLContext.getInstance(protocol.toString());

    // use a CertX509TrustManager since default one will still fail validation for 
    // self-signed certs
    sslContext.init(keyManagers,
            new TrustManager[] { trustedCerts != null ? new CertX509TrustManager(defaultManager, trustedCerts)
                    : new CertX509TrustManager() },
            null);

    return sslContext;

}

From source file:com.machinepublishers.jbrowserdriver.StreamConnectionClient.java

private static SSLContext sslContext() {
    final String property = SettingsManager.settings().ssl();
    if (property != null && !property.isEmpty() && !"null".equals(property)) {
        if ("trustanything".equals(property)) {
            try {
                return SSLContexts.custom().loadTrustMaterial(KeyStore.getInstance(KeyStore.getDefaultType()),
                        new TrustStrategy() {
                            public boolean isTrusted(X509Certificate[] chain, String authType)
                                    throws CertificateException {
                                return true;
                            }/*from   w ww  . j  a  v a2  s  .  c o  m*/
                        }).build();
            } catch (Throwable t) {
                LogsServer.instance().exception(t);
            }
        } else {
            try {
                String location = property;
                location = location.equals("compatible")
                        ? "https://raw.githubusercontent.com/bagder/ca-bundle/master/ca-bundle.crt"
                        : location;
                File cachedPemFile = new File("./pemfile_cached");
                boolean remote = location.startsWith("https://") || location.startsWith("http://");
                if (remote && cachedPemFile.exists()
                        && (System.currentTimeMillis() - cachedPemFile.lastModified() < 48 * 60 * 60 * 1000)) {
                    location = cachedPemFile.getAbsolutePath();
                    remote = false;
                }
                String pemBlocks = null;
                if (remote) {
                    HttpURLConnection remotePemFile = (HttpURLConnection) StreamHandler
                            .defaultConnection(new URL(location));
                    remotePemFile.setRequestMethod("GET");
                    remotePemFile.connect();
                    pemBlocks = Util.toString(remotePemFile.getInputStream(), Util.charset(remotePemFile));
                    cachedPemFile.delete();
                    Files.write(Paths.get(cachedPemFile.getAbsolutePath()), pemBlocks.getBytes("utf-8"));
                } else {
                    pemBlocks = new String(Files.readAllBytes(Paths.get(new File(location).getAbsolutePath())),
                            "utf-8");
                }
                KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
                keyStore.load(null);
                CertificateFactory cf = CertificateFactory.getInstance("X.509");
                Matcher matcher = pemBlock.matcher(pemBlocks);
                boolean found = false;
                while (matcher.find()) {
                    String pemBlock = matcher.group(1).replaceAll("[\\n\\r]+", "");
                    ByteArrayInputStream byteStream = new ByteArrayInputStream(
                            Base64.getDecoder().decode(pemBlock));
                    java.security.cert.X509Certificate cert = (java.security.cert.X509Certificate) cf
                            .generateCertificate(byteStream);
                    String alias = cert.getSubjectX500Principal().getName("RFC2253");
                    if (alias != null && !keyStore.containsAlias(alias)) {
                        found = true;
                        keyStore.setCertificateEntry(alias, cert);
                    }
                }
                if (found) {
                    KeyManagerFactory keyManager = KeyManagerFactory
                            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
                    keyManager.init(keyStore, null);
                    TrustManagerFactory trustManager = TrustManagerFactory
                            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
                    trustManager.init(keyStore);
                    SSLContext context = SSLContext.getInstance("TLS");
                    context.init(keyManager.getKeyManagers(), trustManager.getTrustManagers(), null);
                    return context;
                }
            } catch (Throwable t) {
                LogsServer.instance().exception(t);
            }
        }
    }
    return SSLContexts.createSystemDefault();
}

From source file:org.wso2.extension.siddhi.store.mongodb.util.MongoTableUtils.java

private static SocketFactory extractSocketFactory(String trustStore, String trustStorePassword, String keyStore,
        String keyStorePassword) {
    TrustManager[] trustManagers;
    KeyManager[] keyManagers;/*  www  .ja  v  a 2  s  . c  o m*/

    try (InputStream trustStream = new FileInputStream(trustStore)) {
        char[] trustStorePass = trustStorePassword.toCharArray();
        KeyStore trustStoreJKS = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStoreJKS.load(trustStream, trustStorePass);
        TrustManagerFactory trustFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustFactory.init(trustStoreJKS);
        trustManagers = trustFactory.getTrustManagers();
    } catch (FileNotFoundException e) {
        throw new MongoTableException("Trust store file not found for secure connections to mongodb. "
                + "Trust Store file path : '" + trustStore + "'.", e);
    } catch (IOException e) {
        throw new MongoTableException(
                "I/O Exception in creating trust store for secure connections to mongodb. "
                        + "Trust Store file path : '" + trustStore + "'.",
                e);
    } catch (CertificateException e) {
        throw new MongoTableException("Certificates in the trust store could not be loaded for secure "
                + "connections to mongodb. Trust Store file path : '" + trustStore + "'.", e);
    } catch (NoSuchAlgorithmException e) {
        throw new MongoTableException("The algorithm used to check the integrity of the trust store cannot be "
                + "found. Trust Store file path : '" + trustStore + "'.", e);
    } catch (KeyStoreException e) {
        throw new MongoTableException("Exception in creating trust store, no Provider supports aKeyStoreSpi "
                + "implementation for the specified type. Trust Store file path : '" + trustStore + "'.", e);
    }

    try (InputStream keyStream = new FileInputStream(keyStore)) {
        char[] keyStorePass = keyStorePassword.toCharArray();
        KeyStore keyStoreJKS = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStoreJKS.load(keyStream, keyStorePass);
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStoreJKS, keyStorePass);
        keyManagers = keyManagerFactory.getKeyManagers();
    } catch (FileNotFoundException e) {
        throw new MongoTableException("Key store file not found for secure connections to mongodb. "
                + "Key Store file path : '" + keyStore + "'.", e);
    } catch (IOException e) {
        throw new MongoTableException(
                "I/O Exception in creating trust store for secure connections to mongodb. "
                        + "Key Store file path : '" + keyStore + "'.",
                e);
    } catch (CertificateException e) {
        throw new MongoTableException("Certificates in the trust store could not be loaded for secure "
                + "connections to mongodb. Key Store file path : '" + keyStore + "'.", e);
    } catch (NoSuchAlgorithmException e) {
        throw new MongoTableException("The algorithm used to check the integrity of the trust store cannot be "
                + "found. Key Store file path : '" + keyStore + "'.", e);
    } catch (KeyStoreException e) {
        throw new MongoTableException(
                "Exception in creating trust store, no Provider supports aKeyStoreSpi "
                        + "implementation for the specified type. Key Store file path : '" + keyStore + "'.",
                e);
    } catch (UnrecoverableKeyException e) {
        throw new MongoTableException(
                "Key in the keystore cannot be recovered. " + "Key Store file path : '" + keyStore + "'.", e);
    }

    try {
        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(keyManagers, trustManagers, null);
        SSLContext.setDefault(sslContext);
        return sslContext.getSocketFactory();
    } catch (KeyManagementException e) {
        throw new MongoTableException(
                "Error in validating the key in the key store/ trust store. " + "Trust Store file path : '"
                        + trustStore + "'. " + "Key Store file path : '" + keyStore + "'.",
                e);
    } catch (NoSuchAlgorithmException e) {
        throw new MongoTableException(
                " SSL Algorithm used to create SSL Socket Factory for mongodb connections " + "is not found.",
                e);
    }

}

From source file:org.mule.transport.ldap.util.DSManager.java

public static IoFilterChainBuilder init(final KeyStore ks) throws NamingException {
    SSLContext sslCtx;//from   w w w .java 2 s .  c  o m
    try {
        // Set up key manager factory to use our key store
        String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
        if (algorithm == null) {
            algorithm = "SunX509";
        }
        final KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
        kmf.init(ks, "changeit".toCharArray());

        // Initialize the SSLContext to work with our key managers.
        sslCtx = SSLContext.getInstance("TLS");
        sslCtx.init(kmf.getKeyManagers(), new TrustManager[] { new ServerX509TrustManager() },
                new SecureRandom());

        logger.debug("ssl set");
    } catch (final Exception e) {
        throw (NamingException) new NamingException("Failed to create a SSL context.").initCause(e);
    }

    final DefaultIoFilterChainBuilder chain = new DefaultIoFilterChainBuilder();
    chain.addLast("sslFilter", new SSLFilter(sslCtx));
    return chain;
}

From source file:org.wso2.carbon.identity.application.authentication.endpoint.util.TenantMgtAdminServiceClient.java

/**
 * Create basic SSL connection factory//  www  .j  a va  2  s .c om
 *
 * @throws AuthenticationException
 */
public static void initMutualSSLConnection(boolean hostNameVerificationEnabled) throws AuthenticationException {

    try {
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(keyManagerType);
        keyManagerFactory.init(keyStore, keyStorePassword);
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(trustManagerType);
        trustManagerFactory.init(trustStore);

        // Create and initialize SSLContext for HTTPS communication
        SSLContext sslContext = SSLContext.getInstance(protocol);

        if (hostNameVerificationEnabled) {
            sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
            sslSocketFactory = sslContext.getSocketFactory();

            if (log.isDebugEnabled()) {
                log.debug("Mutual SSL Client initialized with Hostname Verification enabled");
            }
        } else {
            // All the code below is to overcome host name verification failure we get in certificate
            // validation due to self signed certificate.

            // Create empty HostnameVerifier
            HostnameVerifier hv = new HostnameVerifier() {
                @Override
                public boolean verify(String urlHostName, SSLSession session) {
                    return true;
                }
            };

            // Create a trust manager that does not validate certificate chains
            TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
                @Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return new java.security.cert.X509Certificate[0];
                }

                @Override
                public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
                    /*
                         skipped implementation
                    */
                }

                @Override
                public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
                    /*
                         skipped implementation
                     */
                }
            } };

            sslContext.init(keyManagerFactory.getKeyManagers(), trustAllCerts,
                    new java.security.SecureRandom());

            if (log.isDebugEnabled()) {
                log.debug("SSL Context is initialized with trust manager for excluding certificate validation");
            }
            SSLContext.setDefault(sslContext);
            sslSocketFactory = sslContext.getSocketFactory();
            HttpsURLConnection.setDefaultHostnameVerifier(hv);

            if (log.isDebugEnabled()) {
                log.debug("Mutual SSL Client initialized with Hostname Verification disabled");
            }
        }
    } catch (UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException
            | KeyManagementException e) {
        throw new AuthenticationException("Error while trying to load Trust Store.", e);
    }
}