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.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// w w w.  j ava  2  s . co  m
                .httpsIOSessionStrategy(new SSLIOSessionStrategy(sslContext, new NoopHostnameVerifier()));

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

From source file:org.wso2.msf4j.conf.SSLClientContext.java

public SSLClientContext(File keyStore, String keyStorePassword) {

    try {//from  www  .  j  a v  a2 s. com
        KeyManagerFactory kmf = null;
        if (keyStore != null && keyStorePassword != null) {
            KeyStore ks = getKeyStore(keyStore, keyStorePassword);
            kmf = KeyManagerFactory.getInstance("SunX509");
            kmf.init(ks, keyStorePassword.toCharArray());
        }
        clientContext = SSLContext.getInstance(protocol);
        clientContext.init(kmf == null ? null : kmf.getKeyManagers(), TrustManagerFactory.getTrustManagers(),
                null);
    } catch (Exception e) {
        throw new RuntimeException("Failed to initialize the client-side SSLContext", e);
    }
}

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

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

    if (java.security.Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
        java.security.Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    }/*from  w ww  . j a  va 2  s  .c om*/

    try (FileInputStream clientCert = new FileInputStream(new File(clientCertPath));
            FileInputStream key = new FileInputStream(new File(keyPath));
            FileInputStream certificateAuthoritiies = new FileInputStream(new File(caPath))) {
        KeyStore keyStore = PemReader.loadKeyStore(clientCert, key, Optional.ofNullable(keyPassphrase));
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, keyPassphrase.toCharArray());

        KeyStore trustStore = PemReader.loadTrustStore(certificateAuthoritiies);

        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
        builder.sslSocketFactory(new SSLConnectionSocketFactory(sslContext));
        builder.httpsIOSessionStrategy(new SSLIOSessionStrategy(sslContext, new NoopHostnameVerifier()));

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

}

From source file:ucar.httpservices.CustomSSLProtocolSocketFactory.java

private SSLContext trustedauthentication(HttpParams params) throws Exception {
    String keypath = null;/*ww w .j a va  2  s  .  com*/
    String keypassword = null;
    String trustpath = null;
    String trustpassword = null;
    HTTPSSLProvider provider = null;
    if (params == null)
        return null;
    Object o = params.getParameter(HTTPAuthPolicy.PROVIDER);
    if (o == null)
        return null;
    if (!(o instanceof HTTPSSLProvider))
        throw new HTTPException("CustomSSLProtocolSocketFactory: provide is not SSL provider");
    provider = (HTTPSSLProvider) o;
    keypath = provider.getKeystore();
    keypassword = provider.getKeypassword();
    trustpath = provider.getTruststore();
    trustpassword = provider.getTrustpassword();

    TrustManager[] trustmanagers = null;
    KeyManager[] keymanagers = null;

    KeyStore keystore = buildstore(keypath, keypassword, "key");
    if (keystore != null) {
        KeyManagerFactory kmfactory = KeyManagerFactory.getInstance("SunX509");
        kmfactory.init(keystore, keypassword.toCharArray());
        keymanagers = kmfactory.getKeyManagers();
    }
    KeyStore truststore = buildstore(trustpath, trustpassword, "trust");
    if (truststore != null) {
        //todo: TrustManagerFactory trfactory = TrustManagerFactory.getInstance("SunX509");
        //trfactory.init(truststore, trustpassword.toCharArray());
        //trustmanagers = trfactory.getTrustManagers();
        trustmanagers = new TrustManager[] { new CustomX509TrustManager(truststore) };
    }
    if (trustmanagers == null)
        trustmanagers = new TrustManager[] { new CustomX509TrustManager(null) };

    SSLContext sslcontext = SSLContext.getInstance("TSL");
    sslcontext.init(keymanagers, trustmanagers, null);
    return sslcontext;
}

From source file:se.vgregion.delegation.server.Server.java

/**
 * This method sets up the security./*from  w w w.j  ava2 s . c  o  m*/
 * 
 * @param port
 * @throws IOException
 * @throws GeneralSecurityException
 */
private void setupServerEngineFactory(int port) throws IOException, GeneralSecurityException {

    TLSServerParameters tlsParams = new TLSServerParameters();

    String userhome = System.getProperty("user.home");
    String certFilePath = userhome + "/.delegation-service/" + propertiesBean.getCertFileName();

    // String trustStoreFilePath = userhome + "/.delegation-service/prod-truststore.jks";
    String trustStoreFilePath = userhome + "/.delegation-service/" + propertiesBean.getClientAuthCertFilename();

    InputStream resourceAsStream = new FileInputStream(certFilePath);

    KeyStore keyStore = KeyStore.getInstance("PKCS12");

    try {
        keyStore.load(resourceAsStream, propertiesBean.getCertPass().toCharArray());
    } finally {
        resourceAsStream.close();
    }

    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
    keyManagerFactory.init(keyStore, propertiesBean.getCertPass().toCharArray());
    tlsParams.setKeyManagers(keyManagerFactory.getKeyManagers());

    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
    // trustManagerFactory.init(keyStore);

    InputStream is = new FileInputStream(trustStoreFilePath);
    KeyStore trustStore = KeyStore.getInstance("JKS");
    // trustStore.load(is, "password".toCharArray());
    trustStore.load(is, propertiesBean.getClientAuthCertPass().toCharArray());
    trustManagerFactory.init(trustStore);
    TrustManager[] trustMgrs = trustManagerFactory.getTrustManagers();

    tlsParams.setTrustManagers(trustMgrs);

    // FiltersType filter = new FiltersType();
    // filter.getInclude().add(".*");
    // tlsParams.setCipherSuitesFilter(filter);

    ClientAuthentication clientAuth = new ClientAuthentication();
    // clientAuth.setRequired(true);
    // clientAuth.setWant(true);
    clientAuth.setRequired(true);
    clientAuth.setWant(false);
    tlsParams.setClientAuthentication(clientAuth);

    // if (propertiesBean.isClientCertSecurityActive()) {
    // CertificateConstraintsType constraints = new CertificateConstraintsType();
    // DNConstraintsType constraintsType = new DNConstraintsType();
    // // constraintsType.setCombinator(CombinatorType.ANY);
    // System.out.println("propertiesBean.getRegularExpressionClientCert() "
    // + propertiesBean.getRegularExpressionClientCert());
    // String regularExpression = propertiesBean.getRegularExpressionClientCert();
    // // constraintsType.getRegularExpression().add(regularExpression);
    // constraints.setSubjectDNConstraints(constraintsType);
    // tlsParams.setCertConstraints(constraints);
    // }

    engineFactory = new JettyHTTPServerEngineFactory();
    engineFactory.setTLSServerParametersForPort(port, tlsParams);

}

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

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

    if (isBouncyCastleInstalled()) {
        removeBouncyCastle();
        addBouncyCastleOnShutdown = true;
    }

    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.elasticsearch.hadoop.rest.commonshttp.SSLSocketFactory.java

private KeyManager[] loadKeyManagers() throws GeneralSecurityException, IOException {
    if (!StringUtils.hasText(keyStoreLocation)) {
        return null;
    }/*  ww w  .j ava  2  s.  c o m*/

    char[] pass = (StringUtils.hasText(keyStorePass) ? keyStorePass.trim().toCharArray() : null);
    KeyStore keyStore = loadKeyStore(keyStoreLocation, pass);
    KeyManagerFactory kmFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmFactory.init(keyStore, pass);
    return kmFactory.getKeyManagers();
}

From source file:immf.MyWiser.java

private SSLSocketFactory createSslSocketFactory(String keystoreFile, String keyType, String keypasswd) {
    InputStream keyis = null;/*from   w w w. j  a  v  a 2s  .co  m*/
    try {
        keyis = new FileInputStream(keystoreFile);
        KeyStore keyStore = KeyStore.getInstance(keyType);
        keyStore.load(keyis, keypasswd.toCharArray());

        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(keyStore, keypasswd.toCharArray());

        SSLContext context = SSLContext.getInstance("TLS");

        context.init(kmf.getKeyManagers(), null, new SecureRandom());
        return context.getSocketFactory();
    } catch (Exception e) {
        e.printStackTrace();
        return (SSLSocketFactory) SSLSocketFactory.getDefault();
    } finally {
        try {
            keyis.close();
        } catch (Exception e) {
        }
    }
}

From source file:net.lightbody.bmp.proxy.jetty.http.SunJsseListener.java

protected SSLServerSocketFactory createFactory() throws Exception {
    _keystore = System.getProperty(KEYSTORE_PROPERTY, _keystore);

    log.info(KEYSTORE_PROPERTY + "=" + _keystore);

    if (_password == null)
        _password = Password.getPassword(PASSWORD_PROPERTY, null, null);
    log.info(PASSWORD_PROPERTY + "=" + _password.toStarString());

    if (_keypassword == null)
        _keypassword = Password.getPassword(KEYPASSWORD_PROPERTY, null, _password.toString());
    log.info(KEYPASSWORD_PROPERTY + "=" + _keypassword.toStarString());

    KeyStore ks = null;/*w w w .  j  a va 2  s .  com*/

    log.info(KEYSTORE_TYPE_PROPERTY + "=" + _keystore_type);

    if (_keystore_provider_class != null) {
        // find provider.
        // avoid creating another instance if already installed in Security.
        java.security.Provider[] installed_providers = Security.getProviders();
        java.security.Provider myprovider = null;
        for (int i = 0; i < installed_providers.length; i++) {
            if (installed_providers[i].getClass().getName().equals(_keystore_provider_class)) {
                myprovider = installed_providers[i];
                break;
            }
        }
        if (myprovider == null) {
            // not installed yet, create instance and add it
            myprovider = (java.security.Provider) Class.forName(_keystore_provider_class).newInstance();
            Security.addProvider(myprovider);
        }
        log.info(KEYSTORE_PROVIDER_CLASS_PROPERTY + "=" + _keystore_provider_class);
        ks = KeyStore.getInstance(_keystore_type, myprovider.getName());
    } else if (_keystore_provider_name != null) {
        log.info(KEYSTORE_PROVIDER_NAME_PROPERTY + "=" + _keystore_provider_name);
        ks = KeyStore.getInstance(_keystore_type, _keystore_provider_name);
    } else {
        ks = KeyStore.getInstance(_keystore_type);
        log.info(KEYSTORE_PROVIDER_NAME_PROPERTY + "=[DEFAULT]");
    }

    ks.load(new FileInputStream(new File(_keystore)), _password.toString().toCharArray());

    KeyManagerFactory km = KeyManagerFactory.getInstance("SunX509", "SunJSSE");
    km.init(ks, _keypassword.toString().toCharArray());
    KeyManager[] kma = km.getKeyManagers();

    TrustManagerFactory tm = TrustManagerFactory.getInstance("SunX509", "SunJSSE");
    if (_useDefaultTrustStore) {
        tm.init((KeyStore) null);
    } else {
        tm.init(ks);
    }

    TrustManager[] tma = tm.getTrustManagers();

    SSLContext sslc = SSLContext.getInstance("SSL");
    sslc.init(kma, tma, SecureRandom.getInstance("SHA1PRNG"));

    SSLServerSocketFactory ssfc = sslc.getServerSocketFactory();
    log.info("SSLServerSocketFactory=" + ssfc);
    return ssfc;
}

From source file:org.apache.abdera.protocol.client.util.ClientAuthSSLProtocolSocketFactory.java

public Socket createSocket(String host, int port, InetAddress chost, int cport, HttpConnectionParams params)
        throws IOException, UnknownHostException, ConnectTimeoutException {

    SSLContext context;//from   www  .  jav a 2 s . c  om
    SSLSocketFactory factory = null;
    SSLSocket socket = null;
    try {
        KeyManagerFactory kmf;
        context = SSLContext.getInstance(protocol);
        kmf = KeyManagerFactory.getInstance(kmfFactory);
        TrustManager tm = (this.tm != null) ? this.tm : new NonOpTrustManager();
        kmf.init(ks, keyStorePass.toCharArray());
        context.init(kmf.getKeyManagers(), new TrustManager[] { tm }, null);
        factory = context.getSocketFactory();
        socket = (SSLSocket) factory.createSocket(host, port);
        return socket;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}