Example usage for javax.net.ssl KeyManagerFactory getKeyManagers

List of usage examples for javax.net.ssl KeyManagerFactory getKeyManagers

Introduction

In this page you can find the example usage for javax.net.ssl KeyManagerFactory getKeyManagers.

Prototype

public final KeyManager[] getKeyManagers() 

Source Link

Document

Returns one key manager for each type of key material.

Usage

From source file:it.danja.newsmonitor.utils.HttpServer.java

public void init() {

    // Set up the HTTP protocol processor
    HttpProcessor httpproc = HttpProcessorBuilder.create().add(new ResponseDate())
            .add(new ResponseServer("Test/1.1")).add(new ResponseContent()).add(new ResponseConnControl())
            .build();//from  ww w.j ava 2  s . c  o  m

    // Set up request handlers
    UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper();
    reqistry.register("*", new HttpFileHandler(docRoot));

    // Set up the HTTP service
    httpService = new HttpService(httpproc, reqistry);

    if (port == 8443) {
        // Initialize SSL context
        ClassLoader cl = HttpServer.class.getClassLoader();
        URL url = cl.getResource("my.keystore");
        if (url == null) {
            log.info("HttpServer : Keystore not found");
            System.exit(1);
        }
        KeyStore keystore = null;
        try {
            keystore = KeyStore.getInstance("jks");
        } catch (KeyStoreException e) {

            log.error(e.getMessage());
        }
        try {
            keystore.load(url.openStream(), "secret".toCharArray());
        } catch (NoSuchAlgorithmException e) {

            log.error(e.getMessage());
        } catch (CertificateException e) {

            log.error(e.getMessage());
        } catch (IOException e) {

            log.error(e.getMessage());
        }
        KeyManagerFactory kmfactory = null;
        try {
            kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        } catch (NoSuchAlgorithmException e) {

            log.error(e.getMessage());
        }
        try {
            kmfactory.init(keystore, "secret".toCharArray());
        } catch (UnrecoverableKeyException e) {

            log.error(e.getMessage());
        } catch (KeyStoreException e) {

            log.error(e.getMessage());
        } catch (NoSuchAlgorithmException e) {

            log.error(e.getMessage());
        }
        KeyManager[] keymanagers = kmfactory.getKeyManagers();
        SSLContext sslcontext = null;
        try {
            sslcontext = SSLContext.getInstance("TLS");
        } catch (NoSuchAlgorithmException e) {

            log.error(e.getMessage());
        }
        try {
            sslcontext.init(keymanagers, null, null);
        } catch (KeyManagementException e) {

            log.error(e.getMessage());
        }
        this.sf = sslcontext.getServerSocketFactory();
    }
}

From source file:org.jenkinsci.remoting.engine.HandlerLoopbackLoadStress.java

public HandlerLoopbackLoadStress(Config config)
        throws IOException, NoSuchAlgorithmException, CertificateException, KeyStoreException,
        UnrecoverableKeyException, KeyManagementException, OperatorCreationException {
    this.config = config;
    KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
    gen.initialize(2048); // maximum supported by JVM with export restrictions
    keyPair = gen.generateKeyPair();/*from   w w  w  . j ava 2s .  c o  m*/

    Date now = new Date();
    Date firstDate = new Date(now.getTime() + TimeUnit.DAYS.toMillis(10));
    Date lastDate = new Date(now.getTime() + TimeUnit.DAYS.toMillis(-10));

    SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo
            .getInstance(keyPair.getPublic().getEncoded());

    X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
    X500Name subject = nameBuilder.addRDN(BCStyle.CN, getClass().getSimpleName()).addRDN(BCStyle.C, "US")
            .build();

    X509v3CertificateBuilder certGen = new X509v3CertificateBuilder(subject, BigInteger.ONE, firstDate,
            lastDate, subject, subjectPublicKeyInfo);

    JcaX509ExtensionUtils instance = new JcaX509ExtensionUtils();

    certGen.addExtension(X509Extension.subjectKeyIdentifier, false,
            instance.createSubjectKeyIdentifier(subjectPublicKeyInfo));

    ContentSigner signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider(BOUNCY_CASTLE_PROVIDER)
            .build(keyPair.getPrivate());

    certificate = new JcaX509CertificateConverter().setProvider(BOUNCY_CASTLE_PROVIDER)
            .getCertificate(certGen.build(signer));

    char[] password = "password".toCharArray();

    KeyStore store = KeyStore.getInstance("jks");
    store.load(null, password);
    store.setKeyEntry("alias", keyPair.getPrivate(), password, new Certificate[] { certificate });

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(store, password);

    context = SSLContext.getInstance("TLS");
    context.init(kmf.getKeyManagers(), new TrustManager[] { new BlindTrustX509ExtendedTrustManager() }, null);

    mainHub = IOHub.create(executorService);
    // on windows there is a bug whereby you cannot mix ServerSockets and Sockets on the same selector
    acceptorHub = File.pathSeparatorChar == 59 ? IOHub.create(executorService) : mainHub;
    legacyHub = new NioChannelHub(executorService);
    executorService.submit(legacyHub);
    serverSocketChannel = ServerSocketChannel.open();

    JnlpProtocolHandler handler = null;
    for (JnlpProtocolHandler h : new JnlpProtocolHandlerFactory(executorService).withNioChannelHub(legacyHub)
            .withIOHub(mainHub).withSSLContext(context).withPreferNonBlockingIO(!config.bio)
            .withClientDatabase(new JnlpClientDatabase() {
                @Override
                public boolean exists(String clientName) {
                    return true;
                }

                @Override
                public String getSecretOf(@Nonnull String clientName) {
                    return secretFor(clientName);
                }
            }).withSSLClientAuthRequired(false).handlers()) {
        if (config.name.equals(h.getName())) {
            handler = h;
            break;
        }
    }
    if (handler == null) {
        throw new RuntimeException("Unknown handler: " + config.name);
    }
    this.handler = handler;

    acceptor = new Acceptor(serverSocketChannel);
    runtimeMXBean = ManagementFactory.getRuntimeMXBean();
    operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
    _getProcessCpuTime = _getProcessCpuTime(operatingSystemMXBean);
    garbageCollectorMXBeans = new ArrayList<GarbageCollectorMXBean>(
            ManagementFactory.getGarbageCollectorMXBeans());
    Collections.sort(garbageCollectorMXBeans, new Comparator<GarbageCollectorMXBean>() {
        @Override
        public int compare(GarbageCollectorMXBean o1, GarbageCollectorMXBean o2) {
            return o1.getName().compareTo(o2.getName());
        }
    });
    stats = new Stats();
}

From source file:net.java.sip.communicator.impl.certificate.CertificateServiceImpl.java

public SSLContext getSSLContext(String clientCertConfig, X509TrustManager trustManager)
        throws GeneralSecurityException {
    try {/*from   w  w w .  j  a va 2s.c  o m*/
        if (clientCertConfig == null)
            return getSSLContext(trustManager);

        CertificateConfigEntry entry = null;
        for (CertificateConfigEntry e : getClientAuthCertificateConfigs()) {
            if (e.getId().equals(clientCertConfig)) {
                entry = e;
                break;
            }
        }
        if (entry == null)
            throw new GeneralSecurityException(
                    "Client certificate config with id <" + clientCertConfig + "> not found.");

        final KeyManagerFactory kmf = KeyManagerFactory.getInstance("NewSunX509");
        kmf.init(new KeyStoreBuilderParameters(loadKeyStore(entry)));

        return getSSLContext(kmf.getKeyManagers(), trustManager);
    } catch (Exception e) {
        throw new GeneralSecurityException("Cannot init SSLContext", e);
    }
}

From source file:ddf.security.realm.sts.StsRealm.java

/**
 * Setup key store for SSL client./*from   w  ww. jav  a2  s .c o m*/
 */
private void setupKeyStore(TLSClientParameters tlsParams, String keyStorePath, String keyStorePassword) {
    File keyStoreFile = new File(keyStorePath);

    if (keyStoreFile.exists() && keyStorePassword != null) {
        FileInputStream fis = null;
        KeyStore keyStore = null;

        try {
            keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            fis = new FileInputStream(keyStoreFile);

            LOGGER.debug("Loading keyStore");
            keyStore.load(fis, keyStorePassword.toCharArray());

            KeyManagerFactory keyFactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyFactory.init(keyStore, keyStorePassword.toCharArray());
            LOGGER.debug("key manager factory initialized");
            KeyManager[] km = keyFactory.getKeyManagers();
            tlsParams.setKeyManagers(km);
        } catch (FileNotFoundException e) {
            LOGGER.error("Unable to find SSL store: " + keyStorePath, e);
        } catch (IOException e) {
            LOGGER.error("Unable to load key store. " + keyStoreFile, e);
        } catch (CertificateException e) {
            LOGGER.error("Unable to load certificates from key store. " + keyStoreFile, e);
        } catch (KeyStoreException e) {
            LOGGER.error("Unable to read key store: ", e);
        } catch (NoSuchAlgorithmException e) {
            LOGGER.error("Problems creating SSL socket. Usually this is "
                    + "referring to the certificate sent by the server not being trusted by the client.", e);
        } catch (UnrecoverableKeyException e) {
            LOGGER.error("Unable to read key store: ", e);
        } finally {
            IOUtils.closeQuietly(fis);
        }

    }
}

From source file:org.parosproxy.paros.network.SSLConnector.java

public SSLSocketFactory getTunnelSSLSocketFactory(String hostname) {

    //   SSLServerSocketFactory ssf = null;
    // set up key manager to do server authentication

    //   KeyStore ks;
    try {/*from  ww w.ja va  2 s .  com*/
        SSLContext ctx = SSLContext.getInstance(SSL);
        // Normally "SunX509", "IbmX509"...
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());

        SslCertificateService scs = CachedSslCertifificateServiceImpl.getService();
        KeyStore ks = scs.createCertForHost(hostname);

        kmf.init(ks, SslCertificateService.PASSPHRASE);
        java.security.SecureRandom x = new java.security.SecureRandom();
        x.setSeed(System.currentTimeMillis());
        ctx.init(kmf.getKeyManagers(), null, x);

        SSLSocketFactory tunnelSSLFactory = createDecoratedServerSslSocketFactory(ctx.getSocketFactory());

        return tunnelSSLFactory;

    } catch (NoSuchAlgorithmException | KeyStoreException | CertificateException | UnrecoverableKeyException
            | KeyManagementException | InvalidKeyException | NoSuchProviderException | SignatureException
            | IOException e) {
        // Turn into RuntimeException. How to handle this error in a user
        // friendly way?
        throw new RuntimeException(e);
    }
}

From source file:com.datastax.loader.CqlDelimLoad.java

private SSLOptions createSSLOptions() throws KeyStoreException, FileNotFoundException, IOException,
        NoSuchAlgorithmException, KeyManagementException, CertificateException, UnrecoverableKeyException {
    TrustManagerFactory tmf = null;
    KeyStore tks = KeyStore.getInstance("JKS");
    tks.load((InputStream) new FileInputStream(new File(truststorePath)), truststorePwd.toCharArray());
    tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(tks);/*w  ww.j  ava  2  s .c om*/

    KeyManagerFactory kmf = null;
    if (null != keystorePath) {
        KeyStore kks = KeyStore.getInstance("JKS");
        kks.load((InputStream) new FileInputStream(new File(keystorePath)), keystorePwd.toCharArray());
        kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(kks, keystorePwd.toCharArray());
    }

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(kmf != null ? kmf.getKeyManagers() : null, tmf != null ? tmf.getTrustManagers() : null,
            new SecureRandom());

    return JdkSSLOptions.builder().withSSLContext(sslContext).build();
}

From source file:android.core.SSLSocketTest.java

/**
 * Loads a keystore from a base64-encoded String. Returns the KeyManager[]
 * for the result.//from   w  ww.j  a  v  a2 s .com
 */
private KeyManager[] getKeyManagers(String keys) throws Exception {
    byte[] bytes = new Base64().decode(keys.getBytes());
    InputStream inputStream = new ByteArrayInputStream(bytes);

    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(inputStream, PASSWORD.toCharArray());
    inputStream.close();

    String algorithm = KeyManagerFactory.getDefaultAlgorithm();
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(algorithm);
    keyManagerFactory.init(keyStore, PASSWORD.toCharArray());

    return keyManagerFactory.getKeyManagers();
}

From source file:software.betamax.util.DynamicSelfSignedSslEngineSource.java

private void initializeSSLContext() {
    String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
    if (algorithm == null) {
        algorithm = "SunX509";
    }/*  w w w  .  j  ava 2s .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:org.jboss.as.test.integration.security.loginmodules.RemotingLoginModuleTestCase.java

/**
 * Configure {@link SSLContext} and create EJB client properties.
 *
 * @param clientName//w w  w  .j a va  2 s.com
 * @return
 * @throws Exception
 */
private Properties configureEjbClient(String clientName) throws Exception {
    // create new SSLContext based on client keystore and truststore and use this SSLContext instance as a default for this test
    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(
            KeyStoreUtil.getKeyStore(getClientKeystoreFile(clientName), KEYSTORE_PASSWORD.toCharArray()),
            KEYSTORE_PASSWORD.toCharArray());

    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory
            .init(KeyStoreUtil.getKeyStore(CLIENTS_TRUSTSTORE_FILE, KEYSTORE_PASSWORD.toCharArray()));

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

    final Properties env = new Properties();
    env.put("java.naming.factory.initial", "org.jboss.naming.remote.client.InitialContextFactory");
    env.put("java.naming.provider.url", "remote://" + mgmtClient.getMgmtAddress() + ":" + REMOTING_PORT_TEST);
    env.put("jboss.naming.client.ejb.context", "true");
    env.put("jboss.naming.client.connect.options.org.xnio.Options.SASL_POLICY_NOPLAINTEXT", "false");
    env.put(Context.SECURITY_PRINCIPAL, "admin");
    env.put(Context.SECURITY_CREDENTIALS, "testing");

    // SSL related config parameters
    env.put("jboss.naming.client.remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED",
            "true");
    env.put("jboss.naming.client.connect.options.org.xnio.Options.SSL_STARTTLS", "true");
    return env;
}

From source file:org.wso2.carbon.inbound.endpoint.protocol.rabbitmq.RabbitMQConnectionFactory.java

/**
 * Initialize connection factory//ww  w.  j  ava  2  s.  c  om
 */
public void initConnectionFactory() {
    connectionFactory = new ConnectionFactory();
    String hostName = parameters.get(RabbitMQConstants.SERVER_HOST_NAME);
    String portValue = parameters.get(RabbitMQConstants.SERVER_PORT);
    String serverRetryIntervalS = parameters.get(RabbitMQConstants.SERVER_RETRY_INTERVAL);
    String retryIntervalS = parameters.get(RabbitMQConstants.RETRY_INTERVAL);
    String retryCountS = parameters.get(RabbitMQConstants.RETRY_COUNT);
    String heartbeat = parameters.get(RabbitMQConstants.HEARTBEAT);
    String connectionTimeout = parameters.get(RabbitMQConstants.CONNECTION_TIMEOUT);
    String sslEnabledS = parameters.get(RabbitMQConstants.SSL_ENABLED);
    String userName = parameters.get(RabbitMQConstants.SERVER_USER_NAME);
    String password = parameters.get(RabbitMQConstants.SERVER_PASSWORD);
    String virtualHost = parameters.get(RabbitMQConstants.SERVER_VIRTUAL_HOST);

    if (!StringUtils.isEmpty(heartbeat)) {
        try {
            int heartbeatValue = Integer.parseInt(heartbeat);
            connectionFactory.setRequestedHeartbeat(heartbeatValue);
        } catch (NumberFormatException e) {
            //proceeding with rabbitmq default value
            log.warn("Number format error in reading heartbeat value. Proceeding with default");
        }
    }
    if (!StringUtils.isEmpty(connectionTimeout)) {
        try {
            int connectionTimeoutValue = Integer.parseInt(connectionTimeout);
            connectionFactory.setConnectionTimeout(connectionTimeoutValue);
        } catch (NumberFormatException e) {
            //proceeding with rabbitmq default value
            log.warn("Number format error in reading connection timeout value. Proceeding with default");
        }
    }

    if (!StringUtils.isEmpty(sslEnabledS)) {
        try {
            boolean sslEnabled = Boolean.parseBoolean(sslEnabledS);
            if (sslEnabled) {
                String keyStoreLocation = parameters.get(RabbitMQConstants.SSL_KEYSTORE_LOCATION);
                String keyStoreType = parameters.get(RabbitMQConstants.SSL_KEYSTORE_TYPE);
                String keyStorePassword = parameters.get(RabbitMQConstants.SSL_KEYSTORE_PASSWORD);
                String trustStoreLocation = parameters.get(RabbitMQConstants.SSL_TRUSTSTORE_LOCATION);
                String trustStoreType = parameters.get(RabbitMQConstants.SSL_TRUSTSTORE_TYPE);
                String trustStorePassword = parameters.get(RabbitMQConstants.SSL_TRUSTSTORE_PASSWORD);
                String sslVersion = parameters.get(RabbitMQConstants.SSL_VERSION);

                if (StringUtils.isEmpty(keyStoreLocation) || StringUtils.isEmpty(keyStoreType)
                        || StringUtils.isEmpty(keyStorePassword) || StringUtils.isEmpty(trustStoreLocation)
                        || StringUtils.isEmpty(trustStoreType) || StringUtils.isEmpty(trustStorePassword)) {
                    log.warn(
                            "Truststore and keystore information is not provided correctly. Proceeding with default SSL configuration");
                    connectionFactory.useSslProtocol();
                } else {
                    char[] keyPassphrase = keyStorePassword.toCharArray();
                    KeyStore ks = KeyStore.getInstance(keyStoreType);
                    ks.load(new FileInputStream(keyStoreLocation), keyPassphrase);

                    KeyManagerFactory kmf = KeyManagerFactory
                            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
                    kmf.init(ks, keyPassphrase);

                    char[] trustPassphrase = trustStorePassword.toCharArray();
                    KeyStore tks = KeyStore.getInstance(trustStoreType);
                    tks.load(new FileInputStream(trustStoreLocation), trustPassphrase);

                    TrustManagerFactory tmf = TrustManagerFactory
                            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
                    tmf.init(tks);

                    SSLContext c = SSLContext.getInstance(sslVersion);
                    c.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

                    connectionFactory.useSslProtocol(c);
                }
            }
        } catch (Exception e) {
            log.warn("Format error in SSL enabled value. Proceeding without enabling SSL", e);
        }
    }

    if (!StringUtils.isEmpty(retryCountS)) {
        try {
            retryCount = Integer.parseInt(retryCountS);
        } catch (NumberFormatException e) {
            log.warn("Number format error in reading retry count value. Proceeding with default value (3)", e);
        }
    }

    if (!StringUtils.isEmpty(hostName)) {
        connectionFactory.setHost(hostName);
    } else {
        handleException("Host name is not defined");
    }

    try {
        int port = Integer.parseInt(portValue);
        if (port > 0) {
            connectionFactory.setPort(port);
        }
    } catch (NumberFormatException e) {
        handleException("Number format error in port number", e);
    }

    if (!StringUtils.isEmpty(userName)) {
        connectionFactory.setUsername(userName);
    }

    if (!StringUtils.isEmpty(password)) {
        connectionFactory.setPassword(password);
    }

    if (!StringUtils.isEmpty(virtualHost)) {
        connectionFactory.setVirtualHost(virtualHost);
    }

    if (!StringUtils.isEmpty(retryIntervalS)) {
        try {
            retryInterval = Integer.parseInt(retryIntervalS);
        } catch (NumberFormatException e) {
            log.warn(
                    "Number format error in reading retry interval value. Proceeding with default value (30000ms)",
                    e);
        }
    }

    if (!StringUtils.isEmpty(serverRetryIntervalS)) {
        try {
            int serverRetryInterval = Integer.parseInt(serverRetryIntervalS);
            connectionFactory.setNetworkRecoveryInterval(serverRetryInterval);
        } catch (NumberFormatException e) {
            log.warn(
                    "Number format error in reading server retry interval value. Proceeding with default value",
                    e);
        }
    }

    connectionFactory.setAutomaticRecoveryEnabled(true);
    connectionFactory.setTopologyRecoveryEnabled(false);
}