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:org.apache.juddi.samples.JuddiAdminService.java

void printStatusSingleNode(Transport transport, String authtoken) throws Exception {
    String replicationUrl = clerkManager.getClientConfig().getUDDINode(curentnode).getReplicationUrl();

    SSLContext sc = SSLContext.getInstance("SSLv3");

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

    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(new FileInputStream(System.getProperty("javax.net.ssl.keyStore")),
            System.getProperty("javax.net.ssl.keyStorePassword").toCharArray());

    kmf.init(ks, System.getProperty("javax.net.ssl.keyStorePassword").toCharArray());

    sc.init(kmf.getKeyManagers(), null, null);

    UDDIReplicationPortType uddiReplicationPort = new UDDIService().getUDDIReplicationPort();
    ((BindingProvider) uddiReplicationPort).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
            replicationUrl);//from  w ww. ja v  a  2  s  . co  m
    ((BindingProvider) uddiReplicationPort).getRequestContext()
            .put("com.sun.xml.internal.ws.transport.https.client.SSLSocketFactory", sc.getSocketFactory());
    /*((BindingProvider) uddiReplicationPort).getRequestContext()
     .put(
     JAXWSProperties.SSL_SOCKET_FACTORY,
     sc.getSocketFactory());*/

    String doPing = uddiReplicationPort.doPing(new DoPing());
    System.out.println(doPing + ".., success");

}

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

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

    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.apache.geode.internal.net.SocketCreator.java

private KeyManager[] getKeyManagers() throws KeyStoreException, IOException, NoSuchAlgorithmException,
        CertificateException, UnrecoverableKeyException {
    GfeConsoleReader consoleReader = GfeConsoleReaderFactory.getDefaultConsoleReader();

    KeyManager[] keyManagers = null;
    String keyStoreType = sslConfig.getKeystoreType();
    if (StringUtils.isEmpty(keyStoreType)) {
        // read from console, default on empty
        if (consoleReader.isSupported()) {
            keyStoreType = consoleReader
                    .readLine("Please enter the keyStoreType (javax.net.ssl.keyStoreType) : ");
        } else {/*  ww  w .  j a  va2  s.co  m*/
            keyStoreType = KeyStore.getDefaultType();
        }
    }
    KeyStore keyStore = KeyStore.getInstance(keyStoreType);
    String keyStoreFilePath = sslConfig.getKeystore();
    if (StringUtils.isEmpty(keyStoreFilePath)) {
        if (consoleReader.isSupported()) {
            keyStoreFilePath = consoleReader
                    .readLine("Please enter the keyStore location (javax.net.ssl.keyStore) : ");
        } else {
            keyStoreFilePath = System.getProperty("user.home") + System.getProperty("file.separator")
                    + ".keystore";
        }
    }

    FileInputStream fileInputStream = new FileInputStream(keyStoreFilePath);
    String passwordString = sslConfig.getKeystorePassword();
    char[] password = null;
    if (passwordString != null) {
        if (passwordString.trim().equals("")) {
            String encryptedPass = System.getenv("javax.net.ssl.keyStorePassword");
            if (!StringUtils.isEmpty(encryptedPass)) {
                String toDecrypt = "encrypted(" + encryptedPass + ")";
                passwordString = PasswordUtil.decrypt(toDecrypt);
                password = passwordString.toCharArray();
            }
            // read from the console
            if (StringUtils.isEmpty(passwordString) && consoleReader != null) {
                password = consoleReader
                        .readPassword("Please enter password for keyStore (javax.net.ssl.keyStorePassword) : ");
            }
        } else {
            password = passwordString.toCharArray();
        }
    }
    keyStore.load(fileInputStream, password);
    // default algorithm can be changed by setting property "ssl.KeyManagerFactory.algorithm" in
    // security properties
    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, password);
    keyManagers = keyManagerFactory.getKeyManagers();
    // follow the security tip in java doc
    if (password != null) {
        java.util.Arrays.fill(password, ' ');
    }

    KeyManager[] extendedKeyManagers = new KeyManager[keyManagers.length];

    for (int i = 0; i < keyManagers.length; i++)

    {
        extendedKeyManagers[i] = new ExtendedAliasKeyManager(keyManagers[i], sslConfig.getAlias());
    }

    return extendedKeyManagers;
}

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;//  ww w . jav  a 2 s  .c  om
    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);
}

From source file:org.apache.nifi.cluster.coordination.http.replication.okhttp.OkHttpReplicationClient.java

private Tuple<SSLSocketFactory, X509TrustManager> createSslSocketFactory(final NiFiProperties properties) {
    final SSLContext sslContext = SslContextFactory.createSslContext(properties);

    if (sslContext == null) {
        return null;
    }//from w  w  w . j  a  v  a  2 s.com

    try {
        final KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("X509");

        // initialize the KeyManager array to null and we will overwrite later if a keystore is loaded
        KeyManager[] keyManagers = null;

        // we will only initialize the keystore if properties have been supplied by the SSLContextService
        final String keystoreLocation = properties.getProperty(NiFiProperties.SECURITY_KEYSTORE);
        final String keystorePass = properties.getProperty(NiFiProperties.SECURITY_KEYSTORE_PASSWD);
        final String keystoreType = properties.getProperty(NiFiProperties.SECURITY_KEYSTORE_TYPE);

        // prepare the keystore
        final KeyStore keyStore = KeyStore.getInstance(keystoreType);

        try (FileInputStream keyStoreStream = new FileInputStream(keystoreLocation)) {
            keyStore.load(keyStoreStream, keystorePass.toCharArray());
        }

        keyManagerFactory.init(keyStore, keystorePass.toCharArray());
        keyManagers = keyManagerFactory.getKeyManagers();

        // we will only initialize the truststure if properties have been supplied by the SSLContextService
        // load truststore
        final String truststoreLocation = properties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE);
        final String truststorePass = properties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_PASSWD);
        final String truststoreType = properties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_TYPE);

        KeyStore truststore = KeyStore.getInstance(truststoreType);
        truststore.load(new FileInputStream(truststoreLocation), truststorePass.toCharArray());
        trustManagerFactory.init(truststore);

        // TrustManagerFactory.getTrustManagers returns a trust manager for each type of trust material. Since we are getting a trust manager factory that uses "X509"
        // as it's trust management algorithm, we are able to grab the first (and thus the most preferred) and use it as our x509 Trust Manager
        //
        // https://docs.oracle.com/javase/8/docs/api/javax/net/ssl/TrustManagerFactory.html#getTrustManagers--
        final X509TrustManager x509TrustManager;
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
        if (trustManagers[0] != null) {
            x509TrustManager = (X509TrustManager) trustManagers[0];
        } else {
            throw new IllegalStateException("List of trust managers is null");
        }

        // if keystore properties were not supplied, the keyManagers array will be null
        sslContext.init(keyManagers, trustManagerFactory.getTrustManagers(), null);

        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        return new Tuple<>(sslSocketFactory, x509TrustManager);
    } catch (final Exception e) {
        throw new RuntimeException(
                "Failed to create SSL Socket Factory for replicating requests across the cluster");
    }
}

From source file:org.apache.ambari.view.hive.client.Connection.java

SSLSocketFactory getTwoWaySSLSocketFactory() throws SQLException {
    SSLSocketFactory socketFactory = null;

    try {/*from w  ww . j  ava  2 s  .  co m*/
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(
                Utils.HiveAuthenticationParams.SUNX509_ALGORITHM_STRING,
                Utils.HiveAuthenticationParams.SUNJSSE_ALGORITHM_STRING);
        String keyStorePath = authParams.get(Utils.HiveAuthenticationParams.SSL_KEY_STORE);
        String keyStorePassword = authParams.get(Utils.HiveAuthenticationParams.SSL_KEY_STORE_PASSWORD);
        KeyStore sslKeyStore = KeyStore.getInstance(Utils.HiveAuthenticationParams.SSL_KEY_STORE_TYPE);

        if (keyStorePath == null || keyStorePath.isEmpty()) {
            throw new IllegalArgumentException(Utils.HiveAuthenticationParams.SSL_KEY_STORE
                    + " Not configured for 2 way SSL connection, keyStorePath param is empty");
        }
        try (FileInputStream fis = new FileInputStream(keyStorePath)) {
            sslKeyStore.load(fis, keyStorePassword.toCharArray());
        }
        keyManagerFactory.init(sslKeyStore, keyStorePassword.toCharArray());

        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(Utils.HiveAuthenticationParams.SUNX509_ALGORITHM_STRING);
        String trustStorePath = authParams.get(Utils.HiveAuthenticationParams.SSL_TRUST_STORE);
        String trustStorePassword = authParams.get(Utils.HiveAuthenticationParams.SSL_TRUST_STORE_PASSWORD);
        KeyStore sslTrustStore = KeyStore.getInstance(Utils.HiveAuthenticationParams.SSL_TRUST_STORE_TYPE);

        if (trustStorePath == null || trustStorePath.isEmpty()) {
            throw new IllegalArgumentException(Utils.HiveAuthenticationParams.SSL_TRUST_STORE
                    + " Not configured for 2 way SSL connection");
        }
        try (FileInputStream fis = new FileInputStream(trustStorePath)) {
            sslTrustStore.load(fis, trustStorePassword.toCharArray());
        }
        trustManagerFactory.init(sslTrustStore);
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(),
                new SecureRandom());
        socketFactory = new SSLSocketFactory(context);
    } catch (Exception e) {
        throw new SQLException("Error while initializing 2 way ssl socket factory ", e);
    }
    return socketFactory;
}

From source file:com.sat.vcse.automation.utils.http.HttpClient.java

private SSLContext getSSLContext() {

    final String METHOD_NAME = "getSSLContext(): ";
    SSLContext sslContext = null;

    try {//from www  .ja va  2s.  com
        //Get the TrustManager based on client truststore file presence or no
        final TrustManager[] trustManager = getTrustManagers();
        // Configure the SSLContext object with the defined cryptoProtocol 
        sslContext = SSLContext.getInstance(this.cryptoProtocol);

        if (this.isClientAuthEnabled) {
            // Load the Client Keystore
            final KeyManagerFactory kmf = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            final KeyStore clientKeystore = KeyStore.getInstance(KeyStore.getDefaultType());

            InputStream keystoreis = null;
            //see if the file is present otherwise read from class path
            File keStoreFile = new File(this.keystore);
            if (keStoreFile.exists()) {
                keystoreis = new FileInputStream(keStoreFile);
            } else {
                LogHandler.warn("File not found, so trying to read it from class path now");
                keystoreis = HttpClient.class.getResourceAsStream(this.keystore);
            }

            clientKeystore.load(keystoreis, this.keystorePasswd.toCharArray());
            kmf.init(clientKeystore, this.keystorePasswd.toCharArray());
            // Configure the SSLContext object with the Keystore, Truststore and random data 
            sslContext.init(kmf.getKeyManagers(), trustManager, new SecureRandom());

        } else {
            // Configure the SSLContext object with the only a Truststore and random data 
            sslContext.init(null, trustManager, new SecureRandom());
        }

    } catch (Exception exp) {
        LogHandler.error(CLASS_NAME + METHOD_NAME + exp.getMessage());
        throw new CoreRuntimeException(exp, CLASS_NAME + METHOD_NAME + exp.getMessage());
    }

    return sslContext;
}

From source file:com.wwpass.connection.WWPassConnection.java

public WWPassConnection(X509Certificate cert, PKCS8EncodedKeySpec key, int timeoutSec, String spfeAddr)
        throws IOException, GeneralSecurityException {
    timeoutMs = timeoutSec * 1000;/*from  ww w .j  a va2  s . com*/
    SpfeURL = "https://" + spfeAddr + "/";
    // Setting up client certificate and key

    X509Certificate[] chain = { cert };

    KeyFactory kf = KeyFactory.getInstance("RSA");
    PrivateKey privKey = kf.generatePrivate(key);

    KeyStore.PrivateKeyEntry pke = new KeyStore.PrivateKeyEntry(privKey, chain);

    //This adds no security but Java requires to password-protect the key
    byte[] password_bytes = new byte[16];
    (new java.security.SecureRandom()).nextBytes(password_bytes);
    // String password = (new BASE64Encoder()).encode(password_bytes);
    String password = (new Base64()).encodeToString(password_bytes);

    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    keyStore.load(null);

    keyStore.setEntry("WWPass client key", pke, new KeyStore.PasswordProtection(password.toCharArray()));
    keyManagerFactory.init(keyStore, password.toCharArray());

    SPFEContext = SSLContext.getInstance("TLS");

    // Making rootCA certificate
    InputStream is = null;
    CertificateFactory cf;
    X509Certificate rootCA = null;
    try {
        is = new ByteArrayInputStream(WWPassCA_DER);
        cf = CertificateFactory.getInstance("X.509");
        rootCA = (X509Certificate) cf.generateCertificate(is);
    } finally {
        if (is != null) {
            is.close();
        }
    }

    //Creating TrustManager for this CA
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());

    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null);
    ks.setCertificateEntry("WWPass Root CA", rootCA);

    trustManagerFactory.init(ks);

    SPFEContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(),
            new java.security.SecureRandom());
}

From source file:de.betterform.connector.http.ssl.BetterFORMKeyStoreManager.java

private X509KeyManager getCustomX509KeyManager(final URL url, final String password)
        throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException,
        UnrecoverableKeyException {
    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    if (url == null) {
        throw new IllegalArgumentException("BetterFORMKeyStoreManager: Keystore url may not be null");
    }// w w w.j a  v a  2 s .  c o  m

    LOGGER.debug("BetterFORMKeyStoreManager: initializing custom key store");
    KeyStore customKeystore = KeyStore.getInstance(KeyStore.getDefaultType());
    InputStream is = null;
    try {
        is = url.openStream();
        customKeystore.load(is, password != null ? password.toCharArray() : null);
    } finally {
        if (is != null)
            is.close();
    }

    if (LOGGER.isTraceEnabled()) {
        Enumeration aliases = customKeystore.aliases();
        while (aliases.hasMoreElements()) {
            String alias = (String) aliases.nextElement();
            LOGGER.trace("Trusted certificate '" + alias + "':");
            Certificate trustedcert = customKeystore.getCertificate(alias);
            if (trustedcert != null && trustedcert instanceof X509Certificate) {
                X509Certificate cert = (X509Certificate) trustedcert;
                LOGGER.trace("  Subject DN: " + cert.getSubjectDN());
                LOGGER.trace("  Signature Algorithm: " + cert.getSigAlgName());
                LOGGER.trace("  Valid from: " + cert.getNotBefore());
                LOGGER.trace("  Valid until: " + cert.getNotAfter());
                LOGGER.trace("  Issuer: " + cert.getIssuerDN());
            }
        }
    }
    keyManagerFactory.init(customKeystore, password.toCharArray());

    KeyManager[] customX509KeyManagers = keyManagerFactory.getKeyManagers();
    if (customX509KeyManagers != null && customX509KeyManagers.length > 0) {
        for (int i = 0; i < customX509KeyManagers.length; i++) {
            if (customX509KeyManagers[i] instanceof X509KeyManager) {
                return (X509KeyManager) customX509KeyManagers[i];
            }
        }
    }

    return null;
}

From source file:lucee.runtime.tag.Http.java

private void ssl(HttpClientBuilder builder) throws PageException {
    try {//from www.j a v  a  2  s .co m
        // SSLContext sslcontext = SSLContexts.createSystemDefault();
        SSLContext sslcontext = SSLContext.getInstance("TLSv1.2");
        if (!StringUtil.isEmpty(this.clientCert)) {
            if (this.clientCertPassword == null)
                this.clientCertPassword = "";
            File ksFile = new File(this.clientCert);
            KeyStore clientStore = KeyStore.getInstance("PKCS12");
            clientStore.load(new FileInputStream(ksFile), this.clientCertPassword.toCharArray());

            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmf.init(clientStore, this.clientCertPassword.toCharArray());

            sslcontext.init(kmf.getKeyManagers(), null, new java.security.SecureRandom());
        } else {
            sslcontext.init(null, null, new java.security.SecureRandom());
        }
        final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactoryImpl(sslcontext,
                new DefaultHostnameVerifierImpl());
        builder.setSSLSocketFactory(sslsf);
        Registry<ConnectionSocketFactory> reg = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslsf)
                .build();
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(
                new DefaultHttpClientConnectionOperatorImpl(reg), null, -1, TimeUnit.MILLISECONDS); // TODO review -1 setting
        builder.setConnectionManager(cm);
    } catch (Exception e) {
        throw Caster.toPageException(e);
    }
}