Example usage for javax.net.ssl KeyManagerFactory init

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

Introduction

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

Prototype

public final void init(KeyStore ks, char[] password)
        throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException 

Source Link

Document

Initializes this factory with a source of key material.

Usage

From source file:edu.washington.shibboleth.attribute.resolver.dc.rws.HttpDataSource.java

/**
 * Generate a socket factory using supplied key and trust stores 
 */// w  w w .ja  va2  s.  co m
protected SSLConnectionSocketFactory getSocketFactory() throws IOException {
    TrustManager[] trustManagers = null;
    KeyManager[] keyManagers = null;

    try {
        /* trust managers */
        if (caCertificateFile != null) {
            KeyStore trustStore;
            int cn = 0;

            log.info("Setting x509 trust from " + caCertificateFile);

            TrustManagerFactory tmf = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            FileInputStream in = new FileInputStream(caCertificateFile);
            Collection certs = cf.generateCertificates(in);

            trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(null, null);

            Iterator cit = certs.iterator();
            while (cit.hasNext()) {
                X509Certificate cert = (X509Certificate) cit.next();
                log.info(" adding " + cert.getSubjectX500Principal().toString());
                System.out.println(" adding " + cert.getSubjectX500Principal().toString());
                trustStore.setCertificateEntry("CACERT" + cn, cert);
                cn += 1;
            }
            tmf.init(trustStore);
            trustManagers = tmf.getTrustManagers();
        } else { // no verification
            trustManagers = new TrustManager[] { new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                public void checkClientTrusted(X509Certificate[] certs, String authType) {
                    return;
                }

                public void checkServerTrusted(X509Certificate[] certs, String authType) {
                    return;
                }
            } };
        }

        /* key manager */
        if (certificateFile != null && keyFile != null) {
            KeyStore keyStore;
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(null, null);

            FileInputStream in = new FileInputStream(certificateFile);
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            X509Certificate cert = (X509Certificate) cf.generateCertificate(in);
            PKCS1 pkcs = new PKCS1();
            log.info("reading key file: " + keyFile);
            PrivateKey key = pkcs.readKey(keyFile);

            X509Certificate[] chain = new X509Certificate[1];
            chain[0] = cert;
            keyStore.setKeyEntry("CERT", (Key) key, "pw".toCharArray(), chain);
            kmf.init(keyStore, "pw".toCharArray());
            keyManagers = kmf.getKeyManagers();
        }

        /* socket factory */

        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(keyManagers, trustManagers, null);
        return new SSLConnectionSocketFactory(ctx);

    } catch (IOException e) {
        log.error("error reading cert or key error: " + e);
    } catch (KeyStoreException e) {
        log.error("keystore error: " + e);
    } catch (NoSuchAlgorithmException e) {
        log.error("sf error: " + e);
    } catch (KeyManagementException e) {
        log.error("sf error: " + e);
    } catch (CertificateException e) {
        log.error("sf error: " + e);
    } catch (UnrecoverableKeyException e) {
        log.error("sf error: " + e);
    }

    return null;

}

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 {/*from   w  w w  .j  av  a 2  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.wso2.carbon.device.mgt.core.geo.service.GeoLocationProviderServiceImpl.java

/**
 * Initializes the SSL Context//from  ww  w.  j ava 2  s. co m
 */
private SSLContext initSSLConnection(String tenantAdminUser)
        throws NoSuchAlgorithmException, UnrecoverableKeyException, KeyStoreException, KeyManagementException,
        IOException, CertificateException {
    String keyStorePassword = ServerConfiguration.getInstance().getFirstProperty("Security.KeyStore.Password");
    String trustStorePassword = ServerConfiguration.getInstance()
            .getFirstProperty("Security.TrustStore.Password");
    String keyStoreLocation = ServerConfiguration.getInstance().getFirstProperty("Security.KeyStore.Location");
    String trustStoreLocation = ServerConfiguration.getInstance()
            .getFirstProperty("Security.TrustStore.Location");

    //Call to load the keystore.
    KeyStore keyStore = loadKeyStore(keyStoreLocation, keyStorePassword.toCharArray());
    //Call to load the TrustStore.
    KeyStore trustStore = loadTrustStore(trustStoreLocation, trustStorePassword.toCharArray());

    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KEY_MANAGER_TYPE);
    keyManagerFactory.init(keyStore, keyStorePassword.toCharArray());
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TRUST_MANAGER_TYPE);
    trustManagerFactory.init(trustStore);

    // Create and initialize SSLContext for HTTPS communication

    SSLContext sslContext = SSLContext.getInstance(SSLV3);
    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
    SSLContext.setDefault(sslContext);
    return sslContext;
}

From source file:org.kuali.kra.s2s.service.impl.S2SConnectorServiceBase.java

/**
 * This method is to confgiure KeyStore and Truststore for Grants.Gov webservice client
 * @param tlsConfig//  w  w w  .  jav a2  s.co m
 * @param alias
 * @param mulitCampusEnabled
 * @throws S2SException
 */
protected void configureKeyStoreAndTrustStore(TLSClientParameters tlsConfig, String alias,
        boolean mulitCampusEnabled) throws S2SException {
    KeyStore keyStore = s2sCertificateReader.getKeyStore();
    KeyManagerFactory keyManagerFactory;
    try {
        keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        if (alias != null && mulitCampusEnabled) {
            KeyStore keyStoreAlias;
            keyStoreAlias = KeyStore.getInstance(s2sCertificateReader.getJksType());
            Certificate[] certificates = keyStore.getCertificateChain(alias);
            Key key = keyStore.getKey(alias,
                    s2SUtilService.getProperty(s2sCertificateReader.getKeyStorePassword()).toCharArray());
            keyStoreAlias.load(null, null);
            keyStoreAlias.setKeyEntry(alias, key,
                    s2SUtilService.getProperty(s2sCertificateReader.getKeyStorePassword()).toCharArray(),
                    certificates);
            keyManagerFactory.init(keyStoreAlias,
                    s2SUtilService.getProperty(s2sCertificateReader.getKeyStorePassword()).toCharArray());
        } else {
            keyManagerFactory.init(keyStore,
                    s2SUtilService.getProperty(s2sCertificateReader.getKeyStorePassword()).toCharArray());
        }
        KeyManager[] km = keyManagerFactory.getKeyManagers();
        tlsConfig.setKeyManagers(km);
        KeyStore trustStore = s2sCertificateReader.getTrustStore();
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);
        TrustManager[] tm = trustManagerFactory.getTrustManagers();
        tlsConfig.setTrustManagers(tm);
    } catch (NoSuchAlgorithmException e) {
        LOG.error(e);
        throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    } catch (KeyStoreException e) {
        LOG.error(e);
        throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    } catch (UnrecoverableKeyException e) {
        LOG.error(e);
        throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    } catch (CertificateException e) {
        LOG.error(e);
        throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    } catch (IOException e) {
        LOG.error(e);
        throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    }
}

From source file:org.kuali.coeus.propdev.impl.s2s.connect.S2SConnectorServiceBase.java

/**
 * This method is to confgiure KeyStore and Truststore for Grants.Gov webservice client
 * @param tlsConfig//from w w  w.j  av  a  2s  . co  m
 * @param alias
 * @param mulitCampusEnabled
 * @throws S2sCommunicationException
 */
protected void configureKeyStoreAndTrustStore(TLSClientParameters tlsConfig, String alias,
        boolean mulitCampusEnabled) throws S2sCommunicationException {
    KeyStore keyStore = s2sCertificateReader.getKeyStore();
    KeyManagerFactory keyManagerFactory;
    try {
        keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        if (alias != null && mulitCampusEnabled) {
            KeyStore keyStoreAlias;
            keyStoreAlias = KeyStore.getInstance(s2sCertificateReader.getJksType());
            Certificate[] certificates = keyStore.getCertificateChain(alias);
            Key key = keyStore.getKey(alias, s2SConfigurationService
                    .getValueAsString(s2sCertificateReader.getKeyStorePassword()).toCharArray());
            keyStoreAlias.load(null, null);
            keyStoreAlias.setKeyEntry(
                    alias, key, s2SConfigurationService
                            .getValueAsString(s2sCertificateReader.getKeyStorePassword()).toCharArray(),
                    certificates);
            keyManagerFactory.init(keyStoreAlias, s2SConfigurationService
                    .getValueAsString(s2sCertificateReader.getKeyStorePassword()).toCharArray());
        } else {
            keyManagerFactory.init(keyStore, s2SConfigurationService
                    .getValueAsString(s2sCertificateReader.getKeyStorePassword()).toCharArray());
        }
        KeyManager[] km = keyManagerFactory.getKeyManagers();
        tlsConfig.setKeyManagers(km);
        KeyStore trustStore = s2sCertificateReader.getTrustStore();
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);
        TrustManager[] tm = trustManagerFactory.getTrustManagers();
        tlsConfig.setTrustManagers(tm);
    } catch (NoSuchAlgorithmException | KeyStoreException | UnrecoverableKeyException | CertificateException
            | IOException e) {
        LOG.error(e.getMessage(), e);
        throw new S2sCommunicationException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    }
}

From source file:com.predic8.membrane.core.transport.ssl.SSLContext.java

public SSLContext(SSLParser sslParser, ResolverMap resourceResolver, String baseLocation) {
    this.sslParser = sslParser;
    try {/*www .  j a  va 2  s. co m*/
        String algorihm = KeyManagerFactory.getDefaultAlgorithm();
        if (sslParser.getAlgorithm() != null)
            algorihm = sslParser.getAlgorithm();

        KeyManagerFactory kmf = null;
        String keyStoreType = "JKS";
        if (sslParser.getKeyStore() != null) {
            if (sslParser.getKeyStore().getKeyAlias() != null)
                throw new InvalidParameterException("keyAlias is not yet supported.");
            char[] keyPass = "changeit".toCharArray();
            if (sslParser.getKeyStore().getKeyPassword() != null)
                keyPass = sslParser.getKeyStore().getKeyPassword().toCharArray();

            if (sslParser.getKeyStore().getType() != null)
                keyStoreType = sslParser.getKeyStore().getType();
            KeyStore ks = openKeyStore(sslParser.getKeyStore(), "JKS", keyPass, resourceResolver, baseLocation);
            kmf = KeyManagerFactory.getInstance(algorihm);
            kmf.init(ks, keyPass);

            Enumeration<String> aliases = ks.aliases();
            while (aliases.hasMoreElements()) {
                String alias = aliases.nextElement();
                if (ks.isKeyEntry(alias)) {
                    // first key is used by the KeyManagerFactory
                    Certificate c = ks.getCertificate(alias);
                    if (c instanceof X509Certificate) {
                        X509Certificate x = (X509Certificate) c;

                        dnsNames = new ArrayList<String>();

                        Collection<List<?>> subjectAlternativeNames = x.getSubjectAlternativeNames();
                        if (subjectAlternativeNames != null)
                            for (List<?> l : subjectAlternativeNames) {
                                if (l.get(0) instanceof Integer && ((Integer) l.get(0) == 2))
                                    dnsNames.add(l.get(1).toString());
                            }
                    }
                    break;
                }
            }

        }
        TrustManagerFactory tmf = null;
        if (sslParser.getTrustStore() != null) {
            String trustAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
            if (sslParser.getTrustStore().getAlgorithm() != null)
                trustAlgorithm = sslParser.getTrustStore().getAlgorithm();
            KeyStore ks = openKeyStore(sslParser.getTrustStore(), keyStoreType, null, resourceResolver,
                    baseLocation);
            tmf = TrustManagerFactory.getInstance(trustAlgorithm);
            tmf.init(ks);
        }

        TrustManager[] tms = tmf != null ? tmf.getTrustManagers()
                : null /* trust anyone: new TrustManager[] { new NullTrustManager() } */;
        if (sslParser.isIgnoreTimestampCheckFailure())
            tms = new TrustManager[] { new TrustManagerWrapper(tms, true) };

        if (sslParser.getProtocol() != null)
            sslc = javax.net.ssl.SSLContext.getInstance(sslParser.getProtocol());
        else
            sslc = javax.net.ssl.SSLContext.getInstance("TLS");

        sslc.init(kmf != null ? kmf.getKeyManagers() : null, tms, null);

        if (sslParser.getCiphers() != null) {
            ciphers = sslParser.getCiphers().split(",");
            Set<String> supportedCiphers = Sets.newHashSet(sslc.getSocketFactory().getSupportedCipherSuites());
            for (String cipher : ciphers) {
                if (!supportedCiphers.contains(cipher))
                    throw new InvalidParameterException("Unknown cipher " + cipher);
                if (cipher.contains("_RC4_"))
                    log.warn("Cipher " + cipher + " uses RC4, which is deprecated.");
            }
        } else {
            // use all default ciphers except those using RC4
            String supportedCiphers[] = sslc.getSocketFactory().getDefaultCipherSuites();
            ArrayList<String> ciphers = new ArrayList<String>(supportedCiphers.length);
            for (String cipher : supportedCiphers)
                if (!cipher.contains("_RC4_"))
                    ciphers.add(cipher);
            sortCiphers(ciphers);
            this.ciphers = ciphers.toArray(new String[ciphers.size()]);
        }
        if (setUseCipherSuitesOrderMethod == null)
            log.warn(
                    "Cannot set the cipher suite order before Java 8. This prevents Forward Secrecy with some SSL clients.");

        if (sslParser.getProtocols() != null) {
            protocols = sslParser.getProtocols().split(",");
        } else {
            protocols = null;
        }

        if (sslParser.getClientAuth() == null) {
            needClientAuth = false;
            wantClientAuth = false;
        } else if (sslParser.getClientAuth().equals("need")) {
            needClientAuth = true;
            wantClientAuth = true;
        } else if (sslParser.getClientAuth().equals("want")) {
            needClientAuth = false;
            wantClientAuth = true;
        } else {
            throw new RuntimeException("Invalid value '" + sslParser.getClientAuth()
                    + "' in clientAuth: expected 'want', 'need' or not set.");
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:net.java.sip.communicator.impl.certificate.CertificateServiceImpl.java

public SSLContext getSSLContext(X509TrustManager trustManager) throws GeneralSecurityException {
    try {/*  w  w w. ja v a 2s .  com*/
        KeyStore ks = KeyStore
                .getInstance(System.getProperty("javax.net.ssl.keyStoreType", KeyStore.getDefaultType()));
        KeyManagerFactory kmFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());

        String keyStorePassword = System.getProperty("javax.net.ssl.keyStorePassword");
        if (System.getProperty("javax.net.ssl.keyStore") != null) {
            ks.load(new FileInputStream(System.getProperty("javax.net.ssl.keyStore")), null);
        } else {
            ks.load(null, null);
        }

        kmFactory.init(ks, keyStorePassword == null ? null : keyStorePassword.toCharArray());
        return getSSLContext(kmFactory.getKeyManagers(), trustManager);
    } catch (Exception e) {
        throw new GeneralSecurityException("Cannot init SSLContext", e);
    }
}

From source file:edu.washington.shibboleth.attribute.resolver.provider.dataConnector.RwsDataConnector.java

/**
 * This sets the key managers that will be used for all TLS and SSL connections to the ldap. 
 * /*from  w  w w  . ja  v a2 s.  c o m*/
 * @see #clearCache()
 * @see #initializeHttpPool()
 * @see #setSslSocketFactory(SSLSocketFactory)
 * 
 * @param kc <code>X509Credential</code> to create KeyManagers with
 */
public void setSslKeyManagers(X509Credential kc) {
    if (kc != null) {
        try {
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
            keystore.load(null, null);
            keystore.setKeyEntry("ldap_tls_client_auth", kc.getPrivateKey(), "changeit".toCharArray(),
                    kc.getEntityCertificateChain().toArray(new X509Certificate[0]));
            kmf.init(keystore, "changeit".toCharArray());
            sslKeyManagers = kmf.getKeyManagers();
        } catch (GeneralSecurityException e) {
            log.error("Error initializing key managers", e);
        } catch (IOException e) {
            log.error("Error initializing key managers", e);
        }
    }
}