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:org.jivesoftware.smack.XMPPConnection.java

/**
 * The server has indicated that TLS negotiation can start. We now need to secure the
 * existing plain connection and perform a handshake. This method won't return until the
 * connection has finished the handshake or an error occured while securing the connection.
 *
 * @throws Exception if an exception occurs.
 *//*w w  w .  ja  v  a2 s  . c o  m*/
void proceedTLSReceived() throws Exception {
    SSLContext context = SSLContext.getInstance("TLS");
    KeyStore ks = null;
    KeyManager[] kms = null;
    PasswordCallback pcb = null;

    if (config.getCallbackHandler() == null) {
        ks = null;
    } else {
        //System.out.println("Keystore type: "+configuration.getKeystoreType());
        if (config.getKeystoreType().equals("NONE")) {
            ks = null;
            pcb = null;
        } else if (config.getKeystoreType().equals("PKCS11")) {
            try {
                Constructor c = Class.forName("sun.security.pkcs11.SunPKCS11")
                        .getConstructor(InputStream.class);
                String pkcs11Config = "name = SmartCard\nlibrary = " + config.getPKCS11Library();
                ByteArrayInputStream config = new ByteArrayInputStream(pkcs11Config.getBytes());
                Provider p = (Provider) c.newInstance(config);
                Security.addProvider(p);
                ks = KeyStore.getInstance("PKCS11", p);
                pcb = new PasswordCallback("PKCS11 Password: ", false);
                this.config.getCallbackHandler().handle(new Callback[] { pcb });
                ks.load(null, pcb.getPassword());
            } catch (Exception e) {
                ks = null;
                pcb = null;
            }
        } else if (config.getKeystoreType().equals("Apple")) {
            ks = KeyStore.getInstance("KeychainStore", "Apple");
            ks.load(null, null);
            //pcb = new PasswordCallback("Apple Keychain",false);
            //pcb.setPassword(null);
        } else {
            ks = KeyStore.getInstance(config.getKeystoreType());
            try {
                pcb = new PasswordCallback("Keystore Password: ", false);
                config.getCallbackHandler().handle(new Callback[] { pcb });
                ks.load(new FileInputStream(config.getKeystorePath()), pcb.getPassword());
            } catch (Exception e) {
                ks = null;
                pcb = null;
            }
        }
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        try {
            if (pcb == null) {
                kmf.init(ks, null);
            } else {
                kmf.init(ks, pcb.getPassword());
                pcb.clearPassword();
            }
            kms = kmf.getKeyManagers();
        } catch (NullPointerException npe) {
            kms = null;
        }
    }

    // Verify certificate presented by the server
    context.init(kms, new javax.net.ssl.TrustManager[] { new ServerTrustManager(getServiceName(), config) },
            new java.security.SecureRandom());
    Socket plain = socket;
    // Secure the plain connection
    socket = context.getSocketFactory().createSocket(plain, plain.getInetAddress().getHostName(),
            plain.getPort(), true);
    socket.setSoTimeout(0);
    socket.setKeepAlive(true);
    // Initialize the reader and writer with the new secured version
    initReaderAndWriter();
    // Proceed to do the handshake
    ((SSLSocket) socket).startHandshake();
    //if (((SSLSocket) socket).getWantClientAuth()) {
    //    System.err.println("Connection wants client auth");
    //}
    //else if (((SSLSocket) socket).getNeedClientAuth()) {
    //    System.err.println("Connection needs client auth");
    //}
    //else {
    //    System.err.println("Connection does not require client auth");
    // }
    // Set that TLS was successful
    usingTLS = true;

    // Set the new  writer to use
    packetWriter.setWriter(writer);
    // Send a new opening stream to the server
    packetWriter.openStream();
}

From source file:de.metas.procurement.webui.ActiveMQBrokerConfiguration.java

/**
 * @return embedded ActiveMQ broker or <code>null</code>
 *///  w w w  . ja v  a  2 s .com
@Bean
public BrokerService brokerService() throws Exception {
    if (!runEmbeddedBroker) {
        logger.info("Skip creating an ActiveMQ broker service");
        return null;
    }

    final BrokerService brokerService = new BrokerService();

    if (useSSL) {
        final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        {
            final KeyStore keystore = KeyStore.getInstance("JKS");
            final Resource keyStoreResource = Application.getContext().getResource(keyStoreFileResourceURL);
            final InputStream keyStoreStream = keyStoreResource.getInputStream();
            keystore.load(keyStoreStream, keyStorePassword.toCharArray());

            kmf.init(keystore, keyStorePassword.toCharArray());
        }

        final TrustManagerFactory tmf = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        {
            final KeyStore trustStore = KeyStore.getInstance("JKS");
            final Resource trustStoreResource = Application.getContext().getResource(trustStoreFileResourceURL);
            final InputStream trustStoreStream = trustStoreResource.getInputStream();
            trustStore.load(trustStoreStream, trustStorePassword.toCharArray());

            tmf.init(trustStore);
        }

        final SslContext sslContext = new SslContext(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
        brokerService.setSslContext(sslContext);
    }

    //
    // "client" Connector
    {
        final TransportConnector connector = new TransportConnector();
        connector.setUri(new URI(brokerUrl.trim()));
        brokerService.addConnector(connector);
    }

    //
    // "Network of brokers" connector
    if (isSet(networkConnector_discoveryAddress)) {
        final DiscoveryNetworkConnector discoveryNetworkConnector = new DiscoveryNetworkConnector(
                new URI(networkConnector_discoveryAddress.trim()));
        discoveryNetworkConnector.setDuplex(true); // without this, we can send to the other broker, but won't get reposnses

        if (isSet(networkConnector_userName)) {
            discoveryNetworkConnector.setUserName(networkConnector_userName.trim());
        }
        if (isSet(networkConnector_password)) {
            discoveryNetworkConnector.setPassword(networkConnector_password.trim());
        }

        // we need to set ConduitSubscriptions to false,
        // see section "Conduit subscriptions and consumer selectors" on http://activemq.apache.org/networks-of-brokers.html
        discoveryNetworkConnector.setConduitSubscriptions(false);

        logger.info("Adding network connector: {}", networkConnector_discoveryAddress);
        brokerService.addNetworkConnector(discoveryNetworkConnector);
    }

    brokerService.setBrokerName(embeddedBrokerName);
    brokerService.start();
    logger.info("Embedded JMS broker started on URL " + brokerUrl);
    return brokerService;
}

From source file:org.kuali.kra.s2s.service.impl.GrantsGovConnectorServiceImpl.java

/**
 * This method is to confgiure KeyStore and Truststore for Grants.Gov webservice client
 * @param tlsConfig//from w  w w. j a  v a2 s. co m
 * @param alias
 * @param mulitCampusEnabled
 * @throws S2SException
 */
protected void configureKeyStoreAndTrustStore(TLSClientParameters tlsConfig, String alias,
        boolean mulitCampusEnabled) throws S2SException {
    KeyStore keyStore = S2SCertificateReader.getKeyStore();
    KeyManagerFactory keyManagerFactory;
    try {
        keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        if (alias != null && mulitCampusEnabled) {
            KeyStore keyStoreAlias;
            keyStoreAlias = KeyStore.getInstance(JKS_TYPE);
            Certificate[] certificates = keyStore.getCertificateChain(alias);
            Key key = keyStore.getKey(alias, s2SUtilService.getProperty(KEYSTORE_PASSWORD).toCharArray());
            keyStoreAlias.load(null, null);
            keyStoreAlias.setKeyEntry(alias, key, s2SUtilService.getProperty(KEYSTORE_PASSWORD).toCharArray(),
                    certificates);
            keyManagerFactory.init(keyStoreAlias, s2SUtilService.getProperty(KEYSTORE_PASSWORD).toCharArray());
        } else {
            keyManagerFactory.init(keyStore, s2SUtilService.getProperty(KEYSTORE_PASSWORD).toCharArray());
        }
        KeyManager[] km = keyManagerFactory.getKeyManagers();
        tlsConfig.setKeyManagers(km);
        KeyStore trustStore = S2SCertificateReader.getTrustStore();
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);
        TrustManager[] tm = trustManagerFactory.getTrustManagers();
        tlsConfig.setTrustManagers(tm);
    } catch (NoSuchAlgorithmException e) {
        LOG.error(e);
        throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    } catch (KeyStoreException e) {
        LOG.error(e);
        throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    } catch (UnrecoverableKeyException e) {
        LOG.error(e);
        throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    } catch (CertificateException e) {
        LOG.error(e);
        throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    } catch (IOException e) {
        LOG.error(e);
        throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    }
}

From source file:edu.washington.shibboleth.attribute.resolver.provider.dataConnector.RwsDataConnector.java

/**
 * This sets the key managers that will be used for all TLS and SSL connections to the ldap. 
 * /*  www .  j  a v a 2  s  .c o  m*/
 * @see #clearCache()
 * @see #initializeHttpPool()
 * @see #setSslSocketFactory(SSLSocketFactory)
 * 
 * @param kc <code>X509Credential</code> to create KeyManagers with
 */
public void setSslKeyManagers(X509Credential kc) {
    if (kc != null) {
        try {
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
            keystore.load(null, null);
            keystore.setKeyEntry("ldap_tls_client_auth", kc.getPrivateKey(), "changeit".toCharArray(),
                    kc.getEntityCertificateChain().toArray(new X509Certificate[0]));
            kmf.init(keystore, "changeit".toCharArray());
            sslKeyManagers = kmf.getKeyManagers();
        } catch (GeneralSecurityException e) {
            log.error("Error initializing key managers", e);
        } catch (IOException e) {
            log.error("Error initializing key managers", e);
        }
    }
}

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

public SSLContext getSSLContext(X509TrustManager trustManager) throws GeneralSecurityException {
    try {/*w w  w  .j ava2 s . c  om*/
        KeyStore ks = KeyStore
                .getInstance(System.getProperty("javax.net.ssl.keyStoreType", KeyStore.getDefaultType()));
        KeyManagerFactory kmFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());

        String keyStorePassword = System.getProperty("javax.net.ssl.keyStorePassword");
        if (System.getProperty("javax.net.ssl.keyStore") != null) {
            ks.load(new FileInputStream(System.getProperty("javax.net.ssl.keyStore")), null);
        } else {
            ks.load(null, null);
        }

        kmFactory.init(ks, keyStorePassword == null ? null : keyStorePassword.toCharArray());
        return getSSLContext(kmFactory.getKeyManagers(), trustManager);
    } catch (Exception e) {
        throw new GeneralSecurityException("Cannot init SSLContext", e);
    }
}

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

/**
 * Constructor for singleton.//from  ww w . j a  v a 2 s . c  o m
 *
 * @param accessor used to access services.
 */
private SSLServerContext(final ServiceAccessor accessor) {
    LOGGER.info("Configuring HTTPS support");
    this.accessor = accessor;
    final File root = accessor.getConfiguration().getBaseDir();
    final String path = accessor.getConfiguration().get("https.keyStore");
    final String ca = accessor.getConfiguration().get("https.trustStore");
    KeyManagerFactory kmf = null;
    TrustManager[] trusts = null;

    // configure keystore
    if (path == null) {
        kmf = getFakeKeyManagerFactory(root);
        LOGGER.warn(HTTPSWARN);
        trusts = new TrustManager[] { new AcceptAllTrustManager() };
    } else {
        try {
            kmf = getKeyManagerFactoryFromKeyStore(root, path);
        } catch (final KeyStoreException e) {
            throw new RuntimeException("Cannot read the key store file", e);
        }
    }

    // configure trustore
    if (ca == null) {
        LOGGER.info("Using default trust store for client side CA verification");
    } else if ("noCA".equalsIgnoreCase(ca)) {
        trusts = new TrustManager[] { new AcceptAllTrustManager() };
        LOGGER.warn(HTTPSWARN);
    } else {
        try {
            trusts = getTrustManagerFactoryFromKeyStore(root, ca).getTrustManagers();
        } catch (final KeyStoreException e) {
            throw new RuntimeException("Cannot read the trust store file", e);
        }
    }

    try {
        final SSLContext context = SSLContext.getInstance(PROTOCOL);
        context.init(kmf.getKeyManagers(), trusts, null);
        serverContext = context;
    } catch (final Exception e) {
        throw new RuntimeException(HTTPSFAIL + e.getMessage(), e);
    }

}

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 {//from   ww w.j a v a 2  s. c  o  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: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   ww w .  jav  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");

}