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.wso2.carbon.identity.authenticator.PushAuthentication.java

/**
 * Set the client certificate to Default SSL Context
 *
 * @param certificateFile File containing certificate (PKCS12 format)
 * @param certPassword    Password of certificate
 * @throws Exception/*from   w  w  w.j a v  a2 s .c  om*/
 */
public static SSLContext setHttpsClientCert(String certificateFile, String certPassword) throws Exception {
    if (certificateFile == null || !new File(certificateFile).exists()) {
        return null;
    }
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(InweboConstants.SUNFORMAT);
    KeyStore keyStore = KeyStore.getInstance(InweboConstants.PKCSFORMAT);

    InputStream keyInput = new FileInputStream(certificateFile);
    keyStore.load(keyInput, certPassword.toCharArray());

    keyInput.close();
    keyManagerFactory.init(keyStore, certPassword.toCharArray());

    SSLContext context = SSLContext.getInstance(InweboConstants.TLSFORMAT);
    context.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom());
    SSLContext.setDefault(context);
    return context;
}

From source file:org.apache.commons.httpclient.contrib.ssl.AuthSSLProtocolSocketFactory.java

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

From source file:nl.nn.adapterframework.http.AuthSSLProtocolSocketFactory.java

private static KeyManager[] createKeyManagers(final KeyStore keystore, final String password, String algorithm)
        throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {
    if (keystore == null) {
        throw new IllegalArgumentException("Keystore may not be null");
    }/*from  www  . j  a va  2s .  c o m*/
    log.debug("Initializing key manager");
    if (StringUtils.isEmpty(algorithm)) {
        algorithm = KeyManagerFactory.getDefaultAlgorithm();
        log.debug("using default KeyManager algorithm [" + algorithm + "]");
    } else {
        log.debug("using configured KeyManager algorithm [" + algorithm + "]");
    }
    KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(algorithm);
    kmfactory.init(keystore, password != null ? password.toCharArray() : null);
    return kmfactory.getKeyManagers();
}

From source file:org.exoplatform.services.videocall.AuthService.java

protected static KeyManager[] getKeyManagers(String keyStoreType, InputStream keyStoreFile,
        String keyStorePassword) throws Exception {
    KeyStore keyStore = null;//  www  .j  a  v a2  s .com
    try {
        keyStore = KeyStore.getInstance(keyStoreType);
        keyStore.load(keyStoreFile, keyStorePassword.toCharArray());
    } catch (NoSuchAlgorithmException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Java implementation cannot manipulate PKCS12 keystores");
        }
    } catch (KeyStoreException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Java implementation cannot manipulate PKCS12 keystores");
        }
    } catch (CertificateException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Bad key or certificate in " + keyStoreFile, e.getMessage());
        }
    } catch (FileNotFoundException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Could not find or read " + keyStoreFile, e.getMessage());
        }
    } catch (IOException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("PKCS12 password is incorrect or keystore is inconsistent: " + keyStoreFile);
        }
    }

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(keyStore, keyStorePassword.toCharArray());
    return kmf.getKeyManagers();
}

From source file:org.wso2.carbon.identity.application.authentication.endpoint.util.TenantMgtAdminServiceClient.java

/**
 * Create basic SSL connection factory//  w  ww .ja v  a  2 s.c o  m
 *
 * @throws AuthenticationException
 */
public static void initMutualSSLConnection(boolean hostNameVerificationEnabled) throws AuthenticationException {

    try {
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(keyManagerType);
        keyManagerFactory.init(keyStore, keyStorePassword);
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(trustManagerType);
        trustManagerFactory.init(trustStore);

        // Create and initialize SSLContext for HTTPS communication
        SSLContext sslContext = SSLContext.getInstance(protocol);

        if (hostNameVerificationEnabled) {
            sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
            sslSocketFactory = sslContext.getSocketFactory();

            if (log.isDebugEnabled()) {
                log.debug("Mutual SSL Client initialized with Hostname Verification enabled");
            }
        } else {
            // All the code below is to overcome host name verification failure we get in certificate
            // validation due to self signed certificate.

            // Create empty HostnameVerifier
            HostnameVerifier hv = new HostnameVerifier() {
                @Override
                public boolean verify(String urlHostName, SSLSession session) {
                    return true;
                }
            };

            // Create a trust manager that does not validate certificate chains
            TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
                @Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return new java.security.cert.X509Certificate[0];
                }

                @Override
                public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
                    /*
                         skipped implementation
                    */
                }

                @Override
                public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
                    /*
                         skipped implementation
                     */
                }
            } };

            sslContext.init(keyManagerFactory.getKeyManagers(), trustAllCerts,
                    new java.security.SecureRandom());

            if (log.isDebugEnabled()) {
                log.debug("SSL Context is initialized with trust manager for excluding certificate validation");
            }
            SSLContext.setDefault(sslContext);
            sslSocketFactory = sslContext.getSocketFactory();
            HttpsURLConnection.setDefaultHostnameVerifier(hv);

            if (log.isDebugEnabled()) {
                log.debug("Mutual SSL Client initialized with Hostname Verification disabled");
            }
        }
    } catch (UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException
            | KeyManagementException e) {
        throw new AuthenticationException("Error while trying to load Trust Store.", e);
    }
}

From source file:net.jmhertlein.mcanalytics.api.auth.SSLUtil.java

/**
 * Builds an SSLConect that trusts the trust material in the KeyStore
 *
 * @param trustMaterial/*from  ww w. ja  v a  2s  . c o  m*/
 * @return
 */
public static SSLContext buildContext(KeyStore trustMaterial) {
    SSLContext ctx;
    try {
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(trustMaterial);

        KeyManagerFactory keyMgr = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyMgr.init(trustMaterial, new char[0]);

        ctx = SSLContext.getInstance("TLS");
        ctx.init(keyMgr.getKeyManagers(), tmf.getTrustManagers(), null);
    } catch (KeyStoreException | UnrecoverableKeyException | KeyManagementException
            | NoSuchAlgorithmException ex) {
        Logger.getLogger(SSLUtil.class.getName()).log(Level.SEVERE, null, ex);
        ctx = null;
    }

    return ctx;
}

From source file:com.app.mvc.http.ext.AuthSSLProtocolSocketFactory.java

private static KeyManager[] createKeyManagers(final KeyStore keystore, final String password)
        throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {
    if (keystore == null) {
        throw new IllegalArgumentException("Keystore may not be null");
    }//from   w  w  w  . j a  v a 2 s .  com
    log.debug("Initializing key manager");
    KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmfactory.init(keystore, password != null ? password.toCharArray() : null);
    return kmfactory.getKeyManagers();
}

From source file:net.jmhertlein.mcanalytics.api.auth.SSLUtil.java

/**
 * Same as buildContext(), but wraps all X509TrustManagers in a SavableTrustManager to provide
 * UntrustedCertificateExceptions so that when a client connects to a server it does not trust,
 * the program can recover the key and ask the user if they wish to trust it.
 *
 * @param trustMaterial/*from  w  w  w.  ja  va  2 s . c o  m*/
 * @return
 */
public static SSLContext buildClientContext(KeyStore trustMaterial) {
    SSLContext ctx;
    try {
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(trustMaterial);
        ctx = SSLContext.getInstance("TLS");
        //key manager factory go!
        KeyManagerFactory keyMgr = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyMgr.init(trustMaterial, new char[0]);

        TrustManager[] trustManagers = tmf.getTrustManagers();

        for (int i = 0; i < trustManagers.length; i++) {
            if (trustManagers[i] instanceof X509TrustManager) {
                System.out.println("Wrapped a trust manager.");
                trustManagers[i] = new SavableTrustManager((X509TrustManager) trustManagers[i]);
            }
        }

        ctx.init(keyMgr.getKeyManagers(), trustManagers, null);
    } catch (KeyStoreException | UnrecoverableKeyException | KeyManagementException
            | NoSuchAlgorithmException ex) {
        Logger.getLogger(SSLUtil.class.getName()).log(Level.SEVERE, null, ex);
        ctx = null;
    }

    return ctx;
}

From source file:inet.encode.SecureMonitor.java

private static void createHttpsServer() {
    try {/*ww w. j a v  a 2s.  c  om*/
        server = HttpsServer.create(new InetSocketAddress(MONITOR_SERVER_PORT), 0);

        SSLContext sslContext = SSLContext.getInstance("TLS");
        // initialise the keystore
        char[] password = Encoder.KEY_STORE_PASS_PHRASE.toCharArray();
        KeyStore ks = KeyStore.getInstance("JKS");
        FileInputStream fis = new FileInputStream(Encoder.KEY_STORE_PATH);
        ks.load(fis, password);

        // setup the key manager factory
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ks, password);

        // setup the trust manager factory
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
        tmf.init(ks);

        // setup the HTTPS context and parameters
        sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

        server.setHttpsConfigurator(new HttpsConfigurator(sslContext));
        server.setExecutor(java.util.concurrent.Executors.newCachedThreadPool());
        server.start();
    } catch (Exception ex) {
        Logger.log(ex);
    }
}

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;/*  w  w w .j  a v  a2s.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;
}