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.oneis.common.utils.SSLCertificates.java

public static SSLContext load(String keysDirectory, String certsName, String clientCAName, boolean quiet)
        throws Exception {
    // For some indiciation of what's going on early in the boot process
    if (!quiet) {
        System.out.println("Loading " + certsName + " SSL certificates from " + keysDirectory);
    }//from  w w  w  .ja v  a2  s .  c  o  m

    // Get filenames
    String keyPathname = keysDirectory + "/" + certsName + ".key";
    String certPathname = keysDirectory + "/" + certsName + ".crt";
    final String intermediateCertPathnameBase = keysDirectory + "/" + certsName + "-intermediate";
    String clientCAPathname = null;
    if (clientCAName != null) {
        clientCAPathname = keysDirectory + "/" + clientCAName + ".crt";
    }

    if (!new File(keyPathname).exists()) {
        System.out.println("Doesn't exist: " + keyPathname);
        return null;
    }
    if (!new File(certPathname).exists()) {
        System.out.println("Doesn't exist: " + certPathname);
        return null;
    }
    if (clientCAPathname != null) {
        if (!new File(clientCAPathname).exists()) {
            System.out.println("Doesn't exist: " + clientCAPathname);
            return null;
        }
    }

    char[] nullPassword = {};

    PrivateKey privateKey = readPEMPrivateKey(keyPathname);

    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    // Server certificate
    ArrayList<java.security.cert.Certificate> certList = new ArrayList<java.security.cert.Certificate>(4);
    java.security.cert.Certificate cert = cf.generateCertificate(readPEM(certPathname));
    certList.add(cert);
    // Optional intermediate certificates
    int intermediateCounter = 1;
    while (true) {
        String intermediateCertPathname = intermediateCertPathnameBase;
        if (intermediateCounter != 1) {
            intermediateCertPathname += "-" + intermediateCounter;
        }
        intermediateCounter++;
        intermediateCertPathname += ".crt";
        if (new File(intermediateCertPathname).exists()) {
            certList.add(cf.generateCertificate(readPEM(intermediateCertPathname)));
        } else {
            // End of cert list
            break;
        }
    }
    // Optional client CA certificate
    java.security.cert.Certificate clientCACert = null;
    if (clientCAPathname != null) {
        clientCACert = cf.generateCertificate(readPEM(clientCAPathname));
    }
    if (clientCAName != null && clientCACert == null) {
        throw new RuntimeException("Logic error, failed to load client CA cert when required");
    }

    KeyStore ks = KeyStore.getInstance("JKS", "SUN");
    ks.load(null, nullPassword);
    ks.setKeyEntry("ONEIS", (Key) privateKey, "".toCharArray(),
            certList.toArray(new java.security.cert.Certificate[certList.size()]));

    if (clientCACert != null) {
        KeyStore.TrustedCertificateEntry tce = new KeyStore.TrustedCertificateEntry(clientCACert);
        ks.setEntry("CLIENTCA", tce, null);
    }

    // Generate some random Java API stuff, just for entertainment
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
    kmf.init(ks, nullPassword);
    TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
    tmf.init(ks);

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

    if (!quiet) {
        System.out.println(" - server cert chain length " + certList.size()
                + (clientCACert != null ? ", requires client cert" : ", public server"));
    }
    return sslContext;
}

From source file:org.appenders.log4j2.elasticsearch.jest.JKSCertInfo.java

@Override
public void applyTo(HttpClientConfig.Builder clientConfigBuilder) {

    try (FileInputStream keystoreFile = new FileInputStream(new File(keystorePath));
            FileInputStream truststoreFile = new FileInputStream(new File(truststorePath))) {
        KeyStore keyStore = KeyStore.getInstance("jks");
        keyStore.load(keystoreFile, keystorePassword.toCharArray());
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, keystorePassword.toCharArray());

        KeyStore trustStore = KeyStore.getInstance("jks");
        trustStore.load(truststoreFile, truststorePassword.toCharArray());

        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

        // TODO: add support for hostname verification modes
        clientConfigBuilder.sslSocketFactory(new SSLConnectionSocketFactory(sslContext));
        clientConfigBuilder//from   w ww .j av  a  2  s . co m
                .httpsIOSessionStrategy(new SSLIOSessionStrategy(sslContext, new NoopHostnameVerifier()));

    } catch (IOException | GeneralSecurityException e) {
        throw new ConfigurationException(configExceptionMessage, e);
    }
}

From source file:org.apache.ftpserver.ssl.Ssl.java

/**
 * Configure secure server related properties. 
 *///from  w  ww  .  j  a v a2  s. c  o  m
public void configure(Configuration conf) throws FtpException {

    try {

        // get configuration parameters
        m_keystoreFile = conf.getString("keystore-file", "./res/.keystore");
        m_keystorePass = conf.getString("keystore-password", "password");
        m_keystoreType = conf.getString("keystore-type", "JKS");
        m_keystoreAlgorithm = conf.getString("keystore-algorithm", "SunX509");
        m_sslProtocol = conf.getString("ssl-protocol", "TLS");
        m_clientAuthReqd = conf.getBoolean("client-authentication", false);
        m_keyPass = conf.getString("key-password", "password");

        // initialize keystore
        FileInputStream fin = null;
        try {
            fin = new FileInputStream(m_keystoreFile);
            m_keyStore = KeyStore.getInstance(m_keystoreType);
            m_keyStore.load(fin, m_keystorePass.toCharArray());
        } finally {
            IoUtils.close(fin);
        }

        // initialize key manager factory
        m_keyManagerFactory = KeyManagerFactory.getInstance(m_keystoreAlgorithm);
        m_keyManagerFactory.init(m_keyStore, m_keyPass.toCharArray());

        // initialize trust manager factory
        m_trustManagerFactory = TrustManagerFactory.getInstance(m_keystoreAlgorithm);
        m_trustManagerFactory.init(m_keyStore);

        // create ssl context map - the key is the 
        // SSL protocol and the value is SSLContext.
        m_sslContextMap = new HashMap();
    } catch (Exception ex) {
        m_log.fatal("Ssl.configure()", ex);
        throw new FtpException("Ssl.configure()", ex);
    }
}

From source file:org.apache.ftpserver.ssl.SSLTestTemplate.java

protected FTPSClient createFTPClient() throws Exception {
    FTPSClient ftpsClient = new FTPSClient(useImplicit());

    FileInputStream fin = new FileInputStream(FTPCLIENT_KEYSTORE);
    KeyStore store = KeyStore.getInstance("jks");
    store.load(fin, KEYSTORE_PASSWORD.toCharArray());
    fin.close();//from   w w  w .  j av  a2  s . c  om

    // initialize key manager factory
    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(store, KEYSTORE_PASSWORD.toCharArray());

    // initialize trust manager factory
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());

    trustManagerFactory.init(store);

    clientKeyManager = keyManagerFactory.getKeyManagers()[0];
    clientTrustManager = trustManagerFactory.getTrustManagers()[0];

    ftpsClient.setKeyManager(clientKeyManager);
    ftpsClient.setTrustManager(clientTrustManager);

    String auth = getAuthValue();
    if (auth != null) {
        ftpsClient.setAuthValue(auth);

        if (auth.equals("SSL")) {
            ftpsClient.setEnabledProtocols(new String[] { "SSLv3" });
        }
    }
    return ftpsClient;
}

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

private static void setupSslProps(Configuration conf) throws IOException {
    FileInputStream fis = null;//ww w . ja  v a 2  s  . c o  m
    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:it.jnrpe.server.CBindingThread.java

/**
 * Returns the SSL factory to be used to create the Server Socket
 * @throws KeyStoreException /*from www .j  ava  2  s .  c o m*/
 * @throws IOException 
 * @throws FileNotFoundException 
 * @throws CertificateException 
 * @throws UnrecoverableKeyException 
 * @throws KeyManagementException 
 * 
 * @see it.intesa.fi2.client.network.ISSLObjectsFactory#getSSLSocketFactory(String, String, String)
 */
public SSLServerSocketFactory getSSLSocketFactory(String sKeyStoreFile, String sKeyStorePwd,
        String sKeyStoreType) throws KeyStoreException, CertificateException, FileNotFoundException,
        IOException, UnrecoverableKeyException, KeyManagementException {
    if (sKeyStoreFile == null)
        throw new KeyStoreException("KEYSTORE HAS NOT BEEN SPECIFIED");
    if (this.getClass().getClassLoader().getResourceAsStream(sKeyStoreFile) == null)
        throw new KeyStoreException("COULD NOT FIND KEYSTORE '" + sKeyStoreFile + "'");

    if (sKeyStorePwd == null)
        throw new KeyStoreException("KEYSTORE PASSWORD HAS NOT BEEN SPECIFIED");

    SSLContext ctx;
    KeyManagerFactory kmf;

    try {
        ctx = SSLContext.getInstance("SSLv3");

        kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());

        //KeyStore ks = getKeystore(sKeyStoreFile, sKeyStorePwd, sKeyStoreType);
        KeyStore ks = KeyStore.getInstance(sKeyStoreType);
        ks.load(this.getClass().getClassLoader().getResourceAsStream(sKeyStoreFile),
                sKeyStorePwd.toCharArray());

        char[] passphrase = sKeyStorePwd.toCharArray();
        kmf.init(ks, passphrase);
        ctx.init(kmf.getKeyManagers(), null, new java.security.SecureRandom());

    } catch (NoSuchAlgorithmException e) {
        throw new SSLException("Unable to initialize SSLSocketFactory.\n" + e.getMessage());
    }

    return ctx.getServerSocketFactory();
}

From source file:com.screenslicer.common.LenientHttpsConfig.java

private LenientHttpsConfig() {
    AsyncHttpClientConfig configTmp = null;
    SSLContext sslContextTmp = null;
    try {//from  w ww .j  a v a 2  s  .  c om
        AsyncHttpClient client = new AsyncHttpClient();
        configTmp = client.getConfig();
        IOUtils.closeQuietly(client);
        client = null;

        X509Certificate cert = (X509Certificate) CertificateFactory.getInstance("X.509")
                .generateCertificate(CommonUtil.class.getResourceAsStream("screenslicer.internal.cert"));
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null);
        keyStore.setCertificateEntry(cert.getSubjectX500Principal().getName(), cert);
        KeyManagerFactory keyManager = KeyManagerFactory.getInstance("SunX509");
        keyManager.init(keyStore, null);
        TrustManagerFactory trustManager = TrustManagerFactory.getInstance("X509");
        trustManager.init(keyStore);
        sslContextTmp = SSLContext.getInstance("TLS");
        sslContextTmp.init(keyManager.getKeyManagers(), trustManager.getTrustManagers(), null);
    } catch (Throwable t) {
    }
    config = configTmp;
    sslContext = sslContextTmp;
}

From source file:com.github.mrstampy.gameboot.otp.OtpTestConfiguration.java

/**
 * Ssl context.//w  w w  . ja v  a  2  s .  c  o m
 *
 * @return the SSL context
 * @throws Exception
 *           the exception
 */
@Bean(name = SERVER_SSL_CONTEXT)
public SSLContext sslContext() throws Exception {
    char[] password = HARDCODED_NSA_APPROVED_PASSWORD.toCharArray();

    KeyStore keystore = getKeyStore();
    keystore.load(getResource(JKS_LOCATION), password);

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());

    kmf.init(keystore, password);

    return createContext(keystore, kmf);
}

From source file:com.terradue.warhol.auth.ssl.SslAuthenticationConfiguration.java

private KeyManager[] fromSslKeyAndCertificate(String publicCertificateLocation, String provateKeyLocation,
        String sslPassword) {/* w  w  w.ja  v  a2 s  . co  m*/
    File publicCertificate = checkFile(publicCertificateLocation);
    File privateKey = checkFile(provateKeyLocation);

    char[] password;
    if (sslPassword != null) {
        password = sslPassword.toCharArray();
    } else {
        password = new char[] {};
    }

    try {
        final KeyStore store = new KeyMaterial(publicCertificate, privateKey, password).getKeyStore();
        store.load(null, password);

        // initialize key and trust managers -> default behavior
        final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
        // password for key and store have to be the same IIRC
        keyManagerFactory.init(store, password);
        return keyManagerFactory.getKeyManagers();
    } catch (Exception e) {
        throw new IllegalStateException("Impossible to initialize SSL certificate/key", e);
    }
}

From source file:de.metas.procurement.webui.ActiveMQBrokerConfiguration.java

/**
 * @return embedded ActiveMQ broker or <code>null</code>
 *//*from   ww w  . ja v  a  2 s  . co  m*/
@Bean
public BrokerService brokerService() throws Exception {
    if (!runEmbeddedBroker) {
        logger.info("Skip creating an ActiveMQ broker service");
        return null;
    }

    final BrokerService brokerService = new BrokerService();

    if (useSSL) {
        final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        {
            final KeyStore keystore = KeyStore.getInstance("JKS");
            final Resource keyStoreResource = Application.getContext().getResource(keyStoreFileResourceURL);
            final InputStream keyStoreStream = keyStoreResource.getInputStream();
            keystore.load(keyStoreStream, keyStorePassword.toCharArray());

            kmf.init(keystore, keyStorePassword.toCharArray());
        }

        final TrustManagerFactory tmf = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        {
            final KeyStore trustStore = KeyStore.getInstance("JKS");
            final Resource trustStoreResource = Application.getContext().getResource(trustStoreFileResourceURL);
            final InputStream trustStoreStream = trustStoreResource.getInputStream();
            trustStore.load(trustStoreStream, trustStorePassword.toCharArray());

            tmf.init(trustStore);
        }

        final SslContext sslContext = new SslContext(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
        brokerService.setSslContext(sslContext);
    }

    //
    // "client" Connector
    {
        final TransportConnector connector = new TransportConnector();
        connector.setUri(new URI(brokerUrl.trim()));
        brokerService.addConnector(connector);
    }

    //
    // "Network of brokers" connector
    if (isSet(networkConnector_discoveryAddress)) {
        final DiscoveryNetworkConnector discoveryNetworkConnector = new DiscoveryNetworkConnector(
                new URI(networkConnector_discoveryAddress.trim()));
        discoveryNetworkConnector.setDuplex(true); // without this, we can send to the other broker, but won't get reposnses

        if (isSet(networkConnector_userName)) {
            discoveryNetworkConnector.setUserName(networkConnector_userName.trim());
        }
        if (isSet(networkConnector_password)) {
            discoveryNetworkConnector.setPassword(networkConnector_password.trim());
        }

        // we need to set ConduitSubscriptions to false,
        // see section "Conduit subscriptions and consumer selectors" on http://activemq.apache.org/networks-of-brokers.html
        discoveryNetworkConnector.setConduitSubscriptions(false);

        logger.info("Adding network connector: {}", networkConnector_discoveryAddress);
        brokerService.addNetworkConnector(discoveryNetworkConnector);
    }

    brokerService.setBrokerName(embeddedBrokerName);
    brokerService.start();
    logger.info("Embedded JMS broker started on URL " + brokerUrl);
    return brokerService;
}