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:software.betamax.util.DynamicSelfSignedSslEngineSource.java

private void initializeSSLContext() {
    String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
    if (algorithm == null) {
        algorithm = "SunX509";
    }/*from ww w . j ava 2  s.c  om*/

    try {
        final KeyStore ks = KeyStore.getInstance("JKS");
        // ks.load(new FileInputStream("keystore.jks"),
        // "changeit".toCharArray());
        ks.load(new FileInputStream(keyStoreFile), PASSWORD.toCharArray());

        // Set up key manager factory to use our key store
        final KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
        kmf.init(ks, PASSWORD.toCharArray());

        // Set up a trust manager factory to use our key store
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);
        tmf.init(ks);

        TrustManager[] trustManagers = new TrustManager[] { new X509TrustManager() {
            // TrustManager that trusts all servers
            @Override
            public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } };

        KeyManager[] keyManagers = kmf.getKeyManagers();

        // Initialize the SSLContext to work with our key managers.
        sslContext = SSLContext.getInstance(PROTOCOL);
        sslContext.init(keyManagers, trustManagers, null);
    } catch (final Exception e) {
        throw new Error("Failed to initialize the server-side SSLContext", e);
    }
}

From source file:com.bt.pi.api.http.SimpleHttpsServerFactoryBean.java

protected HttpServer getInitializedServer(InetSocketAddress address) throws IOException {
    HttpsServer server = HttpsServer.create(address, getBacklog());
    try {//www. j  a v  a  2 s .c o  m
        SSLContext sslContext = SSLContext.getInstance(sslContextProtocol);

        KeyStore ks = KeyStore.getInstance(keyStoreType);
        InputStream is = keyStoreLocation.getInputStream();
        try {
            ks.load(is, password);
        } catch (EOFException e) {
            LOG.warn(String.format(
                    "Unable to load certificate store %s. This may be possible because https isn't enabled with a valid certificate",
                    keyStoreLocation));
            return null;
        }

        KeyManagerFactory kmf = KeyManagerFactory.getInstance(keyManagerAlgorithm);
        kmf.init(ks, password);

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(trustManagerAlgorithm);
        tmf.init(ks);

        sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

        final SSLEngine m_engine = sslContext.createSSLEngine();

        server.setHttpsConfigurator(new HttpsConfigurator(sslContext) {
            public void configure(HttpsParameters params) {
                params.setSSLParameters(getSSLContext().getDefaultSSLParameters());
                params.setNeedClientAuth(false);
                params.setWantClientAuth(false);
                params.setCipherSuites(m_engine.getEnabledCipherSuites());
                params.setProtocols(m_engine.getEnabledProtocols());
            }
        });
    } catch (Throwable e) {
        throw new IOException("initializing HttpsServer failed due to exception", e);
    }
    return server;
}

From source file:dk.netarkivet.common.distribute.HTTPSRemoteFileRegistry.java

private HTTPSRemoteFileRegistry() {
    FileInputStream keyStoreInputStream = null;
    try {/*  ww w .j  a v a2 s .c  o  m*/
        keyStoreInputStream = new FileInputStream(KEYSTORE_PATH);
        KeyStore store = KeyStore.getInstance(SUN_JCEKS_KEYSTORE_TYPE);
        store.load(keyStoreInputStream, KEYSTORE_PASSWORD.toCharArray());
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(SUN_X509_CERTIFICATE_ALGORITHM);
        kmf.init(store, KEY_PASSWORD.toCharArray());
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(SUN_X509_CERTIFICATE_ALGORITHM);
        tmf.init(store);
        sslContext = SSLContext.getInstance(SSL_PROTOCOL);
        sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(),
                SecureRandom.getInstance(SHA1_PRNG_RANDOM_ALGORITHM));
    } catch (GeneralSecurityException | IOException e) {
        throw new IOFailure("Unable to create secure environment for keystore '" + KEYSTORE_PATH + "'", e);
    } finally {
        IOUtils.closeQuietly(keyStoreInputStream);
    }
}

From source file:edu.internet2.middleware.subject.provider.LdapPEMSocketFactory.java

protected void initManagers() {

    // trust managers
    try {/*from   www .  j a v  a2  s  .  c om*/
        X509Certificate cert = null;
        if (caFilename != null)
            cert = readCertificate(caFilename);
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(null, null);
        ks.setCertificateEntry("CACERT", cert);
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ks);
        trustManagers = tmf.getTrustManagers();
    } catch (Exception e) {
        log.error("ldap source cacert error: " + e);
    }

    // key managers
    if (certFilename != null && keyFilename != null) {
        char[] pw = new char[] { 0 };

        try {
            X509Certificate cert = readCertificate(certFilename);
            PKCS1 pkcs = new PKCS1();
            PrivateKey key = pkcs.readKey(keyFilename);
            KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
            ks.load(null, null);
            X509Certificate[] chain = new X509Certificate[1];
            chain[0] = cert;
            ks.setKeyEntry("CERT", (Key) key, pw, chain);

            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmf.init(ks, pw);
            keyManagers = kmf.getKeyManagers();
        } catch (Exception e) {
            log.error("ldap source cert/key error: " + e);
        }
    }

}

From source file:org.jboss.as.test.syslogserver.TLSSyslogServer.java

/**
 * Creates custom sslContext from keystore and truststore configured in
 *
 * @see org.productivity.java.syslog4j.server.impl.net.tcp.TCPNetSyslogServer#initialize()
 *///w  w w  .  j av a  2  s  .  c om
@Override
public void initialize() throws SyslogRuntimeException {
    super.initialize();

    final SSLTCPNetSyslogServerConfigIF config = (SSLTCPNetSyslogServerConfigIF) this.tcpNetSyslogServerConfig;

    try {
        final char[] keystorePwd = config.getKeyStorePassword().toCharArray();
        final KeyStore keystore = loadKeyStore(config.getKeyStore(), keystorePwd);
        final char[] truststorePassword = config.getTrustStorePassword().toCharArray();
        final KeyStore truststore = loadKeyStore(config.getTrustStore(), truststorePassword);

        final KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keystore, keystorePwd);

        final TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(truststore);

        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
    } catch (Exception e) {
        LOGGER.error("Exception occurred during SSLContext for TLS syslog server initialization", e);
        throw new SyslogRuntimeException(e);
    }
}

From source file:org.cloudcoder.submitsvc.oop.builder.WebappSocketFactory.java

private SSLSocketFactory createSocketFactory() throws IOException, GeneralSecurityException {
    String keyStoreType = "JKS";
    InputStream keyStoreInputStream = this.getClass().getClassLoader().getResourceAsStream(keystoreFilename);
    if (keyStoreInputStream == null) {
        throw new IOException("Could not load keystore " + keystoreFilename);
    }/*from   w  ww. ja v  a2  s. c  o  m*/

    KeyStore keyStore;
    try {
        keyStore = KeyStore.getInstance(keyStoreType);
        keyStore.load(keyStoreInputStream, keystorePassword.toCharArray());
    } finally {
        IOUtils.closeQuietly(keyStoreInputStream);
    }

    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("PKIX", "SunJSSE");
    //trustManagerFactory.init(trustStore);
    // XXX Load the cert (public key) here instead of the private key?
    trustManagerFactory.init(keyStore);

    // TrustManager
    X509TrustManager x509TrustManager = null;
    for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) {
        if (trustManager instanceof X509TrustManager) {
            x509TrustManager = (X509TrustManager) trustManager;
            break;
        }
    }
    if (x509TrustManager == null) {
        throw new IllegalArgumentException("Cannot find x509TrustManager");
    }

    // KeyManager
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509", "SunJSSE");
    keyManagerFactory.init(keyStore, keystorePassword.toCharArray());
    X509KeyManager x509KeyManager = null;
    for (KeyManager keyManager : keyManagerFactory.getKeyManagers()) {
        if (keyManager instanceof X509KeyManager) {
            x509KeyManager = (X509KeyManager) keyManager;
            break;
        }
    }
    if (x509KeyManager == null) {
        throw new NullPointerException();
    }

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(new KeyManager[] { x509KeyManager }, new TrustManager[] { x509TrustManager }, null);

    return sslContext.getSocketFactory();
}

From source file:com.youTransactor.uCube.mdm.MDMManager.java

public void initialize(Context context) {
    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);

    onSharedPreferenceChanged(settings, null);

    settings.registerOnSharedPreferenceChangeListener(this);

    try {// www.java 2  s . com
        KeyStore keystoreCA = KeyStore.getInstance(KEYSTORE_TYPE);
        keystoreCA.load(context.getResources().openRawResource(R.raw.keystore), PWD);

        KeyStore keystoreClient = null;

        File file = context.getFileStreamPath(KEYSTORE_CLIENT_FILENAME);

        if (file.exists()) {
            keystoreClient = KeyStore.getInstance(KEYSTORE_TYPE);
            InputStream in = new FileInputStream(file);
            keystoreClient.load(in, PWD);
        }

        ready = keystoreClient != null && keystoreClient.getKey(MDM_CLIENT_CERT_ALIAS, PWD) != null;

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(keystoreCA);

        KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509");
        kmf.init(keystoreClient, PWD);

        sslContext = SSLContext.getInstance("TLS");

        sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

    } catch (Exception e) {
        LogManager.debug(MDMManager.class.getSimpleName(), "load keystore error", e);
    }
}

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

private KeyManager[] fromSslKeyAndCertificate(String publicCertificateLocation, String provateKeyLocation,
        String sslPassword) {/* w  w  w. j  av  a2s . com*/
    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:ddf.security.settings.impl.SecuritySettingsServiceImpl.java

@Override
public TLSClientParameters getTLSParameters() {
    TLSClientParameters tlsParams = new TLSClientParameters();
    try {/* w ww  .  j a v  a2 s .  c  o  m*/
        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:talkeeg.httpserver.HttpServer.java

private NHttpConnectionFactory<DefaultNHttpServerConnection> createConnectionFactory() {
    NHttpConnectionFactory<DefaultNHttpServerConnection> connFactory;
    if (config.isUseTLS()) {
        try {//w w  w  .j  a  v a 2 s. c o  m
            KeyStore keystore = KeyStore.getInstance("jks");
            char[] password = new char[0];
            keystore.load(null, password);
            final X509Certificate certificate = certManager.getCertificate(OwnedKeyType.USER);
            KeyStore.PrivateKeyEntry entry = new KeyStore.PrivateKeyEntry(
                    ownedKeysManager.getPrivateKey(OwnedKeyType.USER), new Certificate[] { certificate });

            keystore.setEntry("", entry, new KeyStore.PasswordProtection(password));
            KeyManagerFactory kmfactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmfactory.init(keystore, password);
            final KeyManager[] keymanagers = kmfactory.getKeyManagers();
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(keymanagers, null, null);
            connFactory = new SSLNHttpServerConnectionFactory(sslcontext, null, ConnectionConfig.DEFAULT);
        } catch (Exception e) {
            throw new RuntimeException("Can not initialise SSL.", e);
        }
    } else {
        connFactory = new DefaultNHttpServerConnectionFactory(ConnectionConfig.DEFAULT);
    }
    return connFactory;
}