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.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 w w. ja v  a 2 s  . c om*/
                        }).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.signserver.client.cli.defaultimpl.KeyStoreOptions.java

private static void setDefaultSocketFactory(final KeyStore truststore, final KeyStore keystore, String keyAlias,
        char[] keystorePassword)
        throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException, UnrecoverableKeyException {

    final TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
    tmf.init(truststore);/*from www. j a v  a 2s .c  o m*/

    final KeyManager[] keyManagers;
    if (keystore == null) {
        keyManagers = null;
    } else {
        if (keyAlias == null) {
            keyAlias = keystore.aliases().nextElement();
        }
        final KeyManagerFactory kKeyManagerFactory = KeyManagerFactory.getInstance("SunX509");
        kKeyManagerFactory.init(keystore, keystorePassword);
        keyManagers = kKeyManagerFactory.getKeyManagers();
        for (int i = 0; i < keyManagers.length; i++) {
            if (keyManagers[i] instanceof X509KeyManager) {
                keyManagers[i] = new AliasKeyManager((X509KeyManager) keyManagers[i], keyAlias);
            }
        }
    }

    final SSLContext context = SSLContext.getInstance("TLS");
    context.init(keyManagers, tmf.getTrustManagers(), new SecureRandom());

    SSLSocketFactory factory = context.getSocketFactory();
    HttpsURLConnection.setDefaultSSLSocketFactory(factory);
}

From source file:org.asynchttpclient.test.TestUtils.java

private static KeyManager[] createKeyManagers() throws GeneralSecurityException, IOException {
    KeyStore ks = KeyStore.getInstance("JKS");
    try (InputStream keyStoreStream = TestUtils.class.getClassLoader()
            .getResourceAsStream("ssltest-cacerts.jks")) {
        char[] keyStorePassword = "changeit".toCharArray();
        ks.load(keyStoreStream, keyStorePassword);
    }//from www. ja v a 2 s.c o m
    assert (ks.size() > 0);

    // Set up key manager factory to use our key store
    char[] certificatePassword = "changeit".toCharArray();
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
    kmf.init(ks, certificatePassword);

    // Initialize the SSLContext to work with our key managers.
    return kmf.getKeyManagers();
}

From source file:net.timewalker.ffmq4.listeners.tcp.io.TcpListener.java

private SSLContext createSSLContext() throws JMSException {
    try {//  w w w  . ja  v a 2  s  .  c om
        String sslProtocol = settings.getStringProperty(FFMQCoreSettings.TRANSPORT_TCP_SSL_PROTOCOL, "SSLv3");
        String keyManagerAlgorithm = settings
                .getStringProperty(FFMQCoreSettings.TRANSPORT_TCP_SSL_KEYMANAGER_ALGORITHM, "SunX509");
        String keyStoreType = settings.getStringProperty(FFMQCoreSettings.TRANSPORT_TCP_SSL_KEYSTORE_TYPE,
                "JKS");
        String keyStorePath = settings.getStringProperty(FFMQCoreSettings.TRANSPORT_TCP_SSL_KEYSTORE_PATH,
                "../conf/server-keystore.jks");
        String keyStorePass = settings.getStringProperty(FFMQCoreSettings.TRANSPORT_TCP_SSL_KEYSTORE_PASWORD,
                "ffmqpass");
        String keyPass = settings.getStringProperty(FFMQCoreSettings.TRANSPORT_TCP_SSL_KEYSTORE_KEY_PASSWORD,
                "ffmqpass");

        SSLContext sslContext = SSLContext.getInstance(sslProtocol);
        log.debug("Created an SSL context : protocol=[" + sslContext.getProtocol() + "] provider=["
                + sslContext.getProvider() + "]");

        // Load available keys
        KeyManager[] keyManagers;
        File keyStoreFile = new File(keyStorePath);
        if (!keyStoreFile.canRead())
            throw new FFMQException("Cannot read keystore file : " + keyStoreFile.getAbsolutePath(),
                    "FS_ERROR");

        KeyStore ks = KeyStore.getInstance(keyStoreType);
        log.debug("Created keystore : type=[" + ks.getType() + "] provider=[" + ks.getProvider() + "]");
        char ksPass[] = keyStorePass.toCharArray();
        char ctPass[] = keyPass.toCharArray();
        log.debug("Loading keystore from " + keyStoreFile.getAbsolutePath());
        InputStream kis = new FileInputStream(keyStoreFile);
        ks.load(kis, ksPass);
        kis.close();

        KeyManagerFactory kmf = KeyManagerFactory.getInstance(keyManagerAlgorithm);
        log.debug("Created KeyManagerFactory : algorithm=[" + kmf.getAlgorithm() + "] provider=["
                + kmf.getProvider() + "]");
        log.debug("Initializing KeyManagerFactory with keystore ...");
        kmf.init(ks, ctPass);

        keyManagers = kmf.getKeyManagers();

        sslContext.init(keyManagers, null, null);

        return sslContext;
    } catch (JMSException e) {
        throw e;
    } catch (Exception e) {
        throw new FFMQException("Cannot create SSL context", "NETWORK_ERROR", e);
    }
}

From source file:org.wildfly.test.integration.elytron.sasl.mgmt.ExternalMgmtSaslTestCase.java

/**
 * Get the key manager backed by the specified key store.
 *
 * @return the initialized key manager.//from  w w w. j  a va 2  s.c om
 */
private static X509ExtendedKeyManager getKeyManager(final File ksFile) throws Exception {
    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(loadKeyStore(ksFile), KEYSTORE_PASSWORD.toCharArray());

    for (KeyManager current : keyManagerFactory.getKeyManagers()) {
        if (current instanceof X509ExtendedKeyManager) {
            return (X509ExtendedKeyManager) current;
        }
    }

    throw new IllegalStateException("Unable to obtain X509ExtendedKeyManager.");
}

From source file:be.solidx.hot.nio.http.SSLContextBuilder.java

private KeyManagerFactory handleClientKeyCertURLProvided(Map<String, Object> options)
        throws SSLContextInitializationException {

    InputStream keyInputStream = null;
    InputStream certInputStream = null;

    try {//  w w w.j av a2 s.  c o  m
        KeyManagerFactory keyManagerFactory = null;
        KeyStore keyStore = KeyStore.getInstance(JKS);
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");

        byte[] key = IOUtils.toByteArray(getInputStream(new URI(options.get(KEY).toString())));
        Certificate certCertificate = certificateFactory
                .generateCertificate(getInputStream(new URI(options.get(CERT).toString())));
        char[] password = options.get(PASSPHRASE).toString().toCharArray();

        keyStore.load(null, null);
        // No CA needed, just add pivate key and associated public key to a keystore
        keyStore.setKeyEntry(KEY, SSLUtils.toPrivateKey(new ByteArrayInputStream(key)), password,
                new Certificate[] { certCertificate });

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

        return keyManagerFactory;
    } catch (NullPointerException | UnrecoverableKeyException | KeyStoreException | CertificateException
            | NoSuchAlgorithmException | IOException | URISyntaxException | InvalidKeySpecException e) {
        throw new SSLContextInitializationException(e);
    } finally {
        if (keyInputStream != null) {
            try {
                keyInputStream.close();
            } catch (IOException e) {
            }
        }
        if (certInputStream != null) {
            try {
                certInputStream.close();
            } catch (IOException e) {
            }
        }
    }
}

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

private KeyManager[] getKeyManagers() {
    KeyManager[] kmList = null;/*w w  w. jav  a  2 s  .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.glite.slcs.httpclient.ssl.ExtendedProtocolSocketFactory.java

private KeyManager[] createKeyManagers(KeyStore keystore, String password)
        throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {
    if (keystore == null) {
        throw new IllegalArgumentException("Keystore may not be null");
    }//from w w w . ja  v  a 2 s. c  o  m
    if (password == null) {
        throw new IllegalArgumentException("Keystore password may not be null");
    }
    LOG.debug("Initializing key manager");
    KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmfactory.init(keystore, password.toCharArray());
    return kmfactory.getKeyManagers();
}

From source file:ucar.nc2.util.net.EasySSLProtocolSocketFactory.java

private SSLContext createSSLContext(HttpConnectionParams params, String host, int port) throws HTTPException {
    SSLContext sslcontext = null;
    KeyManager[] keymanagers = null;
    KeyStore keystore = null;//from  ww  w  .java2s. c o  m
    KeyStore truststore = null;
    TrustManager[] trustmanagers = null;

    String keypassword = null;
    String keypath = null;
    String trustpassword = null;
    String trustpath = null;

    try {

        // Get the HTTPAuthProvider
        HTTPAuthProvider provider;
        provider = (HTTPAuthProvider) params.getParameter(CredentialsProvider.PROVIDER);
        if (provider == null)
            return stdauthenticate();

        // Abuse the getCredentials() api
        Credentials creds = null;
        try {
            creds = provider.getCredentials(HTTPSSLScheme.Default, null, 0, false);
            if (creds == null)
                return stdauthenticate();
        } catch (CredentialsNotAvailableException e) {
            return stdauthenticate();
        }

        HTTPSSLProvider sslprovider = (creds == null ? null : (HTTPSSLProvider) creds);
        if (sslprovider == null)
            return stdauthenticate();

        keypath = (String) sslprovider.getKeystore();
        keypassword = (String) sslprovider.getKeypassword();
        trustpath = (String) sslprovider.getTruststore();
        trustpassword = (String) sslprovider.getTrustpassword();

        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) };
        } else {
            trustmanagers = new TrustManager[] { new EasyX509TrustManager(null) };
        }

        sslcontext = SSLContext.getInstance("SSL");
        sslcontext.init(keymanagers, trustmanagers, null);

        return sslcontext;

    } catch (KeyManagementException e) {
        throw new HTTPException("Key Management exception: " + e.getMessage());
    } 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());
    }
}

From source file:com.naryx.tagfusion.cfm.http.cfHttpConnection.java

private DefaultHttpClient getHttpClient(File pKeyFile, String pKeyPassword)
        throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException,
        UnrecoverableKeyException, KeyManagementException {
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
    KeyStore keyStore = KeyStore.getInstance("PKCS12");

    InputStream keyInput = null;// w  w w. j a  v  a  2  s .c  o m
    try {
        keyInput = new FileInputStream(pKeyFile);
        keyStore.load(keyInput, pKeyPassword.toCharArray());
    } finally {
        if (keyInput != null)
            try {
                keyInput.close();
            } catch (IOException ignored) {
            }
    }

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

    SSLSocketFactory sf = new SSLSocketFactory(keyStore, pKeyPassword);
    sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    registry.register(new Scheme("https", sf, 443));

    ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

    return new DefaultHttpClient(ccm, params);
}