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:ddf.security.settings.impl.SecuritySettingsServiceImpl.java

@Override
public TLSClientParameters getTLSParameters() {
    TLSClientParameters tlsParams = new TLSClientParameters();
    try {/* www. ja va2 s .c  om*/
        TrustManagerFactory trustFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustFactory.init(trustStore);
        TrustManager[] tm = trustFactory.getTrustManagers();
        tlsParams.setTrustManagers(tm);

        KeyManagerFactory keyFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyFactory.init(keyStore, keystorePassword.toCharArray());
        KeyManager[] km = keyFactory.getKeyManagers();
        tlsParams.setKeyManagers(km);
    } catch (NoSuchAlgorithmException | KeyStoreException | UnrecoverableKeyException e) {
        LOGGER.warn(
                "Could not fully load keystore/truststore into TLSParameters. Parameters may not be fully functional.",
                e);
    }

    FiltersType filter = new FiltersType();
    filter.getInclude().addAll(SSL_ALLOWED_ALGORITHMS);
    filter.getExclude().addAll(SSL_DISALLOWED_ALGORITHMS);
    tlsParams.setCipherSuitesFilter(filter);

    return tlsParams;
}

From source file:com.budrotech.jukebox.service.ssl.SSLSocketFactory.java

private static SSLContext createSSLContext(String algorithm, final KeyStore keystore,
        final String keyStorePassword, final SecureRandom random, final TrustStrategy trustStrategy)
        throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, KeyManagementException {
    if (algorithm == null) {
        algorithm = TLS;//from  ww w . ja  va  2s  .c o m
    }

    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keystore, keyStorePassword != null ? keyStorePassword.toCharArray() : null);
    KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(keystore);

    TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();

    if (trustManagers != null && trustStrategy != null) {
        for (int i = 0; i < trustManagers.length; i++) {
            TrustManager tm = trustManagers[i];

            if (tm instanceof X509TrustManager) {
                trustManagers[i] = new TrustManagerDecorator((X509TrustManager) tm, trustStrategy);
            }
        }
    }

    SSLContext sslcontext = SSLContext.getInstance(algorithm);
    sslcontext.init(keyManagers, trustManagers, random);

    return sslcontext;
}

From source file:org.wisdom.engine.ssl.SSLServerContext.java

private KeyManagerFactory getKeyManagerFactoryFromKeyStore(final File maybeRoot, final String path)
        throws KeyStoreException {
    KeyManagerFactory kmf;//from  ww  w  . j  a v  a2 s . c om
    File file = new File(path);
    if (!file.isFile()) {
        // Second chance.
        file = new File(maybeRoot, path);
    }

    LOGGER.info("\t key store: " + file.getAbsolutePath());
    final KeyStore keyStore = KeyStore
            .getInstance(accessor.getConfiguration().getWithDefault("https.keyStoreType", "JKS"));
    LOGGER.info("\t key store type: " + keyStore.getType());
    LOGGER.info("\t key store provider: " + keyStore.getProvider());
    final char[] password = accessor.getConfiguration().getWithDefault("https.keyStorePassword", "")
            .toCharArray();
    LOGGER.info("\t key store password length: " + password.length);
    final String algorithm = accessor.getConfiguration().getWithDefault("https.keyStoreAlgorithm",
            KeyManagerFactory.getDefaultAlgorithm());
    LOGGER.info("\t key store algorithm: " + algorithm);
    if (file.isFile()) {
        FileInputStream stream = null;
        try {
            stream = new FileInputStream(file);
            keyStore.load(stream, password);
            kmf = KeyManagerFactory.getInstance(algorithm);
            kmf.init(keyStore, password);
        } catch (final Exception e) {
            throw new RuntimeException(HTTPSFAIL + e.getMessage(), e);
        } finally {
            IOUtils.closeQuietly(stream);
        }
    } else {
        throw new RuntimeException(
                "Cannot load key store from '" + file.getAbsolutePath() + "', " + "the file does not exist");
    }
    return kmf;
}

From source file:org.springframework.vault.config.ClientHttpRequestFactoryFactory.java

private static KeyManagerFactory createKeyManagerFactory(Resource keystoreFile, String storePassword)
        throws GeneralSecurityException, IOException {

    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());

    loadKeyStore(keystoreFile, storePassword, keyStore);

    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore,/*from  ww w  . j  a  va  2 s .  co m*/
            StringUtils.hasText(storePassword) ? storePassword.toCharArray() : new char[0]);

    return keyManagerFactory;
}

From source file:ddf.catalog.source.opensearch.SecureRemoteConnectionImpl.java

/**
 * Creates a new SSLSocketFactory from a truststore and keystore. This is used during SSL
 * communications with the server.//from  w  w w  .jav a 2 s.c  om
 * 
 * @param trustStoreLoc
 *            File path to the truststore.
 * @param trustStorePass
 *            Password to the truststore.
 * @param keyStoreLoc
 *            File path to the keystore.
 * @param keyStorePass
 *            Password to the keystore.
 * @return new SSLSocketFactory instance containing the trust and key stores.
 * @throws KeyStoreException
 * @throws IOException
 * @throws CertificateException
 * @throws NoSuchAlgorithmException
 * @throws UnrecoverableKeyException
 * @throws KeyManagementException
 */
public SSLSocketFactory createSocket(String trustStoreLoc, String trustStorePass, String keyStoreLoc,
        String keyStorePass) throws KeyStoreException, NoSuchAlgorithmException, CertificateException,
        IOException, UnrecoverableKeyException, KeyManagementException {
    String methodName = "createSocket";
    LOGGER.debug("ENTERING: " + methodName);

    LOGGER.debug("trustStoreLoc = " + trustStoreLoc);
    FileInputStream trustFIS = new FileInputStream(trustStoreLoc);
    LOGGER.debug("keyStoreLoc = " + keyStoreLoc);
    FileInputStream keyFIS = new FileInputStream(keyStoreLoc);

    // truststore stuff
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    try {
        LOGGER.debug("Loading trustStore");
        trustStore.load(trustFIS, trustStorePass.toCharArray());
    } finally {
        IOUtils.closeQuietly(trustFIS);
    }

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(trustStore);
    LOGGER.debug("trust manager factory initialized");

    // keystore stuff
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    try {
        LOGGER.debug("Loading keyStore");
        keyStore.load(keyFIS, keyStorePass.toCharArray());
    } finally {
        IOUtils.closeQuietly(keyFIS);
    }
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(keyStore, keyStorePass.toCharArray());
    LOGGER.debug("key manager factory initialized");

    // ssl context
    SSLContext sslCtx = SSLContext.getInstance("TLS");
    sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

    LOGGER.debug("EXITING: " + methodName);

    return sslCtx.getSocketFactory();
}

From source file:org.apache.nifi.elasticsearch.ElasticSearchClientServiceImpl.java

private SSLContext buildSslContext(SSLContextService sslService) throws IOException, CertificateException,
        NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, KeyManagementException {
    KeyStore keyStore = KeyStore.getInstance(sslService.getKeyStoreType());
    KeyStore trustStore = KeyStore.getInstance("JKS");

    try (final InputStream is = new FileInputStream(sslService.getKeyStoreFile())) {
        keyStore.load(is, sslService.getKeyStorePassword().toCharArray());
    }//  w w w. jav  a2  s . c  om

    try (final InputStream is = new FileInputStream(sslService.getTrustStoreFile())) {
        trustStore.load(is, sslService.getTrustStorePassword().toCharArray());
    }

    final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(keyStore, sslService.getKeyStorePassword().toCharArray());
    final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(keyStore);
    SSLContext context1 = SSLContext.getInstance(sslService.getSslAlgorithm());
    context1.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());
    return context1;
}

From source file:com.twinsoft.convertigo.engine.MySSLSocketFactory.java

private SSLContext createEasySSLContext()
        throws NoSuchProviderException, NoSuchAlgorithmException, KeyManagementException,
        UnrecoverableKeyException, KeyStoreException, CertificateException, IOException {
    Engine.logCertificateManager.debug("(MySSLSocketFactory) Creating SSL context");

    String algorithm = KeyManagerFactory.getDefaultAlgorithm();
    Engine.logCertificateManager.debug("(MySSLSocketFactory) Using KeyManager algorithm " + algorithm);

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);

    String keyStoreType = keyStore.endsWith(".pkcs11") ? "pkcs11" : "pkcs12";
    Engine.logCertificateManager.debug("(MySSLSocketFactory) Key store type: " + keyStoreType);

    String alias = null;//from  w ww.j  av a  2 s  .c o m
    KeyStore ks, ts;
    char[] passPhrase;

    if (keyStore.equals("") || (keyStore.endsWith(".udv"))) {
        ks = KeyStore.getInstance(keyStoreType);
        ks.load(null, keyStorePassword.toCharArray());
        kmf.init(ks, null);
    } else {
        File file = new File(keyStore);

        Properties properties = new Properties();
        properties.load(
                new FileInputStream(Engine.CERTIFICATES_PATH + CertificateManager.STORES_PROPERTIES_FILE_NAME));
        String p = properties.getProperty(file.getName(), "");
        int i = p.indexOf('/');
        if (i != -1) {
            alias = p.substring(i + 1);
        }

        if (keyStoreType.equals("pkcs11")) {
            String providerName = file.getName();
            providerName = "SunPKCS11-" + providerName.substring(0, providerName.lastIndexOf('.'));
            Engine.logCertificateManager.debug("(MySSLSocketFactory) Provider name: '" + providerName + "'");

            String pinCode;
            if (i == -1) {
                pinCode = Crypto2.decodeFromHexString(p);
            } else {
                pinCode = Crypto2.decodeFromHexString(p.substring(0, i));
            }

            Engine.logCertificateManager.debug("(MySSLSocketFactory) PIN code: " + pinCode);

            ks = KeyStore.getInstance("pkcs11", providerName);
            ks.load((InputStream) null, pinCode.toCharArray());
            kmf.init(ks, null);
        } else {
            ks = KeyStore.getInstance(keyStoreType);
            passPhrase = keyStorePassword.toCharArray();
            ks.load(new FileInputStream(keyStore), passPhrase);
            kmf.init(ks, passPhrase);
        }
    }
    Engine.logCertificateManager.debug("(MySSLSocketFactory) Client alias: "
            + (alias == null ? "<to be chosen by the security implementor>" : alias));

    ts = KeyStore.getInstance("jks");
    passPhrase = trustStorePassword.toCharArray();
    if (trustStore.equals(""))
        ts.load(null, passPhrase);
    else
        ts.load(new FileInputStream(trustStore), passPhrase);

    algorithm = TrustManagerFactory.getDefaultAlgorithm();
    Engine.logCertificateManager.debug("(MySSLSocketFactory) Using TrustManager algorithm " + algorithm);

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);
    tmf.init(ts);

    TrustManager[] tm = { TRUST_MANAGER };

    MyX509KeyManager xkm = new MyX509KeyManager((X509KeyManager) kmf.getKeyManagers()[0], ks, ts, alias);

    Engine.logCertificateManager
            .debug("(MySSLSocketFactory) trusting all certificates : " + trustAllServerCertificates);

    //SSLContext context = SSLContext.getInstance("SSLv3");
    SSLContext context = SSLContext.getInstance("TLS");
    if (trustAllServerCertificates)
        context.init(new KeyManager[] { xkm }, tm, null);
    else
        context.init(new KeyManager[] { xkm }, tmf.getTrustManagers(), null);

    Engine.logCertificateManager.debug("(MySSLSocketFactory) SSL context created: " + context.getProtocol());
    return context;
}

From source file:gov.niem.ws.util.SecurityUtil.java

public static KeyManager[] createKeyManagers(KeyPair clientKey, X509Certificate clientCert)
        throws GeneralSecurityException, IOException {
    // Create a new empty key store.
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(null);/*from   w w  w. ja  v  a2s. c om*/

    Certificate[] chain = { clientCert };

    // The KeyStore requires a password for key entries.
    char[] password = { ' ' };

    // Since we never write out the key store, we don't bother protecting
    // the key.
    ks.setEntry("client-key", new KeyStore.PrivateKeyEntry(clientKey.getPrivate(), chain),
            new KeyStore.PasswordProtection(password));

    // Shove the key store in a KeyManager.
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(ks, password);
    return kmf.getKeyManagers();
}

From source file:org.apache.felix.karaf.jaas.config.impl.ResourceKeystoreInstance.java

public KeyManager[] getKeyManager(String algorithm, String keyAlias)
        throws KeystoreIsLocked, NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException {
    if (isKeystoreLocked()) {
        throw new KeystoreIsLocked("Keystore '" + name + "' is locked.");
    }//w  w w.ja  v a  2 s  .  c  o m
    if (!loadKeystoreData()) {
        return null;
    }
    KeyManagerFactory keyFactory = KeyManagerFactory.getInstance(algorithm);
    keyFactory.init(keystore, (char[]) keyPasswords.get(keyAlias));
    return keyFactory.getKeyManagers();
}

From source file:ucar.httpservices.CustomSSLProtocolSocketFactory.java

private SSLContext trustedauthentication(HttpParams params) throws Exception {
    String keypath = null;/*from   w  w  w .ja v  a2s. c o  m*/
    String keypassword = null;
    String trustpath = null;
    String trustpassword = null;
    HTTPSSLProvider provider = null;
    if (params == null)
        return null;
    Object o = params.getParameter(HTTPAuthPolicy.PROVIDER);
    if (o == null)
        return null;
    if (!(o instanceof HTTPSSLProvider))
        throw new HTTPException("CustomSSLProtocolSocketFactory: provide is not SSL provider");
    provider = (HTTPSSLProvider) o;
    keypath = provider.getKeystore();
    keypassword = provider.getKeypassword();
    trustpath = provider.getTruststore();
    trustpassword = provider.getTrustpassword();

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

    KeyStore keystore = buildstore(keypath, keypassword, "key");
    if (keystore != null) {
        KeyManagerFactory kmfactory = KeyManagerFactory.getInstance("SunX509");
        kmfactory.init(keystore, keypassword.toCharArray());
        keymanagers = kmfactory.getKeyManagers();
    }
    KeyStore truststore = buildstore(trustpath, trustpassword, "trust");
    if (truststore != null) {
        //todo: TrustManagerFactory trfactory = TrustManagerFactory.getInstance("SunX509");
        //trfactory.init(truststore, trustpassword.toCharArray());
        //trustmanagers = trfactory.getTrustManagers();
        trustmanagers = new TrustManager[] { new CustomX509TrustManager(truststore) };
    }
    if (trustmanagers == null)
        trustmanagers = new TrustManager[] { new CustomX509TrustManager(null) };

    SSLContext sslcontext = SSLContext.getInstance("TSL");
    sslcontext.init(keymanagers, trustmanagers, null);
    return sslcontext;
}