Example usage for javax.net.ssl TrustManagerFactory init

List of usage examples for javax.net.ssl TrustManagerFactory init

Introduction

In this page you can find the example usage for javax.net.ssl TrustManagerFactory init.

Prototype

public final void init(ManagerFactoryParameters spec) throws InvalidAlgorithmParameterException 

Source Link

Document

Initializes this factory with a source of provider-specific trust material.

Usage

From source file:org.apache.synapse.transport.nhttp.config.ServerConnFactoryBuilder.java

protected SSLContextDetails createSSLContext(final OMElement keyStoreEl, final OMElement trustStoreEl,
        final OMElement cientAuthEl, final OMElement httpsProtocolsEl,
        final RevocationVerificationManager verificationManager, final String sslProtocol) throws AxisFault {

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

    if (keyStoreEl != null) {
        String location = getValueOfElementWithLocalName(keyStoreEl, "Location");
        String type = getValueOfElementWithLocalName(keyStoreEl, "Type");
        String storePassword = getValueOfElementWithLocalName(keyStoreEl, "Password");
        String keyPassword = getValueOfElementWithLocalName(keyStoreEl, "KeyPassword");

        FileInputStream fis = null;
        try {/*  w w  w  .  j  a v a  2s.  co m*/
            KeyStore keyStore = KeyStore.getInstance(type);
            fis = new FileInputStream(location);
            if (log.isInfoEnabled()) {
                log.debug(name + " Loading Identity Keystore from : " + location);
            }

            keyStore.load(fis, storePassword.toCharArray());

            KeyManagerFactory kmfactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmfactory.init(keyStore, keyPassword.toCharArray());
            keymanagers = kmfactory.getKeyManagers();
            if (log.isInfoEnabled() && keymanagers != null) {
                for (KeyManager keymanager : keymanagers) {
                    if (keymanager instanceof X509KeyManager) {
                        X509KeyManager x509keymanager = (X509KeyManager) keymanager;
                        Enumeration<String> en = keyStore.aliases();
                        while (en.hasMoreElements()) {
                            String s = en.nextElement();
                            X509Certificate[] certs = x509keymanager.getCertificateChain(s);
                            if (certs == null)
                                continue;
                            for (X509Certificate cert : certs) {
                                log.debug(name + " Subject DN: " + cert.getSubjectDN());
                                log.debug(name + " Issuer DN: " + cert.getIssuerDN());
                            }
                        }
                    }
                }
            }

        } catch (GeneralSecurityException gse) {
            log.error(name + " Error loading Key store : " + location, gse);
            throw new AxisFault("Error loading Key store : " + location, gse);
        } catch (IOException ioe) {
            log.error(name + " Error opening Key store : " + location, ioe);
            throw new AxisFault("Error opening Key store : " + location, ioe);
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException ignore) {
                }
            }
        }
    }

    if (trustStoreEl != null) {
        String location = getValueOfElementWithLocalName(trustStoreEl, "Location");
        String type = getValueOfElementWithLocalName(trustStoreEl, "Type");
        String storePassword = getValueOfElementWithLocalName(trustStoreEl, "Password");

        FileInputStream fis = null;
        try {
            KeyStore trustStore = KeyStore.getInstance(type);
            fis = new FileInputStream(location);
            if (log.isInfoEnabled()) {
                log.debug(name + " Loading Trust Keystore from : " + location);
            }

            trustStore.load(fis, storePassword.toCharArray());
            TrustManagerFactory trustManagerfactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerfactory.init(trustStore);
            trustManagers = trustManagerfactory.getTrustManagers();

        } catch (GeneralSecurityException gse) {
            log.error(name + " Error loading Key store : " + location, gse);
            throw new AxisFault("Error loading Key store : " + location, gse);
        } catch (IOException ioe) {
            log.error(name + " Error opening Key store : " + location, ioe);
            throw new AxisFault("Error opening Key store : " + location, ioe);
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException ignore) {
                }
            }
        }
    }
    final String s = cientAuthEl != null ? cientAuthEl.getText() : null;
    final SSLClientAuth clientAuth;
    if ("optional".equalsIgnoreCase(s)) {
        clientAuth = SSLClientAuth.OPTIONAL;
    } else if ("require".equalsIgnoreCase(s)) {
        clientAuth = SSLClientAuth.REQUIRED;
    } else {
        clientAuth = null;
    }

    String[] httpsProtocols = null;
    final String configuredHttpsProtocols = httpsProtocolsEl != null ? httpsProtocolsEl.getText() : null;
    if (configuredHttpsProtocols != null && configuredHttpsProtocols.trim().length() != 0) {
        String[] configuredValues = configuredHttpsProtocols.trim().split(",");
        List<String> protocolList = new ArrayList<String>(configuredValues.length);
        for (String protocol : configuredValues) {
            if (!protocol.trim().isEmpty()) {
                protocolList.add(protocol.trim());
            }
        }

        httpsProtocols = protocolList.toArray(new String[protocolList.size()]);
    }

    try {
        final String sslProtocolValue = sslProtocol != null ? sslProtocol : "TLS";
        SSLContext sslContext = SSLContext.getInstance(sslProtocolValue);
        sslContext.init(keymanagers, trustManagers, null);

        ServerSSLSetupHandler sslSetupHandler = (clientAuth != null || httpsProtocols != null)
                ? new ServerSSLSetupHandler(clientAuth, httpsProtocols, verificationManager)
                : null;

        return new SSLContextDetails(sslContext, sslSetupHandler);
    } catch (GeneralSecurityException gse) {
        log.error(name + " Unable to create SSL context with the given configuration", gse);
        throw new AxisFault("Unable to create SSL context with the given configuration", gse);
    }
}

From source file:com.ubergeek42.WeechatAndroid.service.RelayService.java

private void createKeystore() {
    try {/*from  w w  w  .ja  v a2  s  .  c o  m*/
        sslKeystore.load(null, null);
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init((KeyStore) null);
        // Copy current certs into our keystore so we can use it...
        // TODO: don't actually do this...
        X509TrustManager xtm = (X509TrustManager) tmf.getTrustManagers()[0];
        for (X509Certificate cert : xtm.getAcceptedIssuers()) {
            sslKeystore.setCertificateEntry(cert.getSubjectDN().getName(), cert);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    saveKeystore();
}

From source file:mitm.common.security.ca.handlers.ejbca.EJBCACertificateRequestHandler.java

private EjbcaWS getEjbcaWS() throws CAException {
    if (ejbcaWS == null) {
        try {// www .ja va 2 s. c  om
            JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();

            factory.setServiceClass(EjbcaWS.class);
            factory.setAddress(requestHandlerSettings.getWebServiceURL().toExternalForm());
            factory.setServiceName(EJBCAConst.SERVICE_NAME);
            EjbcaWS localEjbcaWS = (EjbcaWS) factory.create();

            KeyManagerFactory keyManagerFactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());

            char[] password = requestHandlerSettings.getKeyStorePassword() != null
                    ? requestHandlerSettings.getKeyStorePassword().toCharArray()
                    : null;

            keyManagerFactory.init(requestHandlerSettings.getKeyStore(), password);

            KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();

            Client proxy = ClientProxy.getClient(localEjbcaWS);

            TLSClientParameters tlsClientParameters = new TLSClientParameters();

            tlsClientParameters.setDisableCNCheck(requestHandlerSettings.isDisableCNCheck());

            if (requestHandlerSettings.isSkipCertificateCheck()) {
                /*
                 * Use a TrustManager that skips all checks 
                 */
                tlsClientParameters.setTrustManagers(new TrustManager[] { new TrustAllX509TrustManager() });
            } else {
                KeyStore trustStore = requestHandlerSettings.getTrustStore();

                if (trustStore != null) {
                    /*
                     * Use the provided trust store
                     */
                    TrustManagerFactory trustManagerFactory = TrustManagerFactory
                            .getInstance(TrustManagerFactory.getDefaultAlgorithm());

                    trustManagerFactory.init(trustStore);

                    tlsClientParameters.setTrustManagers(trustManagerFactory.getTrustManagers());
                }
            }

            tlsClientParameters.setKeyManagers(keyManagers);

            HTTPConduit conduit = (HTTPConduit) proxy.getConduit();

            conduit.setTlsClientParameters(tlsClientParameters);

            ejbcaWS = localEjbcaWS;
        } catch (NoSuchAlgorithmException e) {
            throw new CAException(e);
        } catch (UnrecoverableKeyException e) {
            throw new CAException(e);
        } catch (KeyStoreException e) {
            throw new CAException(e);
        }
    }

    return ejbcaWS;
}

From source file:com.evolveum.midpoint.prism.crypto.AESProtector.java

/**
 * @throws SystemException if jceks keystore is not available on {@link AESProtector#getKeyStorePath}
 *//*from w ww.  j av  a2s .  c  o  m*/
public void init() {
    InputStream stream = null;
    try {
        // Test if use file or classpath resource
        File f = new File(getKeyStorePath());
        if (f.exists()) {
            LOGGER.info("Using file keystore at {}", getKeyStorePath());
            if (!f.canRead()) {
                LOGGER.error("Provided keystore file {} is unreadable.", getKeyStorePath());
                throw new EncryptionException(
                        "Provided keystore file " + getKeyStorePath() + " is unreadable.");
            }
            stream = new FileInputStream(f);

            // Use class path keystore
        } else {
            LOGGER.warn("Using default keystore from classpath ({}).", getKeyStorePath());
            // Read from class path

            stream = AESProtector.class.getClassLoader().getResourceAsStream(getKeyStorePath());
            // ugly dirty hack to have second chance to find keystore on
            // class path
            if (stream == null) {
                stream = AESProtector.class.getClassLoader()
                        .getResourceAsStream("com/../../" + getKeyStorePath());
            }
        }
        // Test if we have valid stream
        if (stream == null) {
            throw new EncryptionException("Couldn't load keystore as resource '" + getKeyStorePath() + "'");
        }
        // Load keystore
        keyStore.load(stream, getKeyStorePassword().toCharArray());
        stream.close();

        // Initialze trust manager list

        TrustManagerFactory tmFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmFactory.init(keyStore);
        trustManagers = new ArrayList<TrustManager>();
        for (TrustManager trustManager : tmFactory.getTrustManagers()) {
            trustManagers.add(trustManager);
        }

        //init apache crypto library
        Init.init();

    } catch (Exception ex) {
        LOGGER.error("Unable to work with keystore {}, reason {}.",
                new Object[] { getKeyStorePath(), ex.getMessage() }, ex);
        throw new SystemException(ex.getMessage(), ex);
    }
}

From source file:org.apache.axis2.transport.rabbitmq.RabbitMQConnectionFactory.java

/**
 * Initialize connection factory//  w  ww  .java2 s  . c o  m
 */
private 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(
                            "Trustore 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);
}

From source file:org.eclipse.emf.emfstore.client.model.connectionmanager.KeyStoreManager.java

/**
 * Returns a SSL Context. This is need for encryption, used by the
 * SSLSocketFactory.//from   w  w  w  .  ja  v  a  2s . c o m
 * 
 * @return SSL Context
 * @throws CertificateStoreException
 *             in case of failure retrieving the context
 */
public SSLContext getSSLContext() throws CertificateStoreException {
    try {
        loadKeyStore();
        KeyManagerFactory managerFactory = KeyManagerFactory.getInstance("SunX509");
        managerFactory.init(keyStore, KEYSTOREPASSWORD.toCharArray());
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
        trustManagerFactory.init(keyStore);
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(managerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });

        return sslContext;
    } catch (NoSuchAlgorithmException e) {
        throw new CertificateStoreException("Loading certificate failed!", e);
    } catch (UnrecoverableKeyException e) {
        throw new CertificateStoreException("Loading certificate failed!", e);
    } catch (KeyStoreException e) {
        throw new CertificateStoreException("Loading certificate failed!", e);
    } catch (KeyManagementException e) {
        throw new CertificateStoreException("Loading certificate failed!", e);
    }
}

From source file:org.apache.synapse.transport.nhttp.config.ClientConnFactoryBuilder.java

private SSLContext createSSLContext(OMElement keyStoreElt, OMElement trustStoreElt, boolean novalidatecert)
        throws AxisFault {

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

    if (keyStoreElt != null) {
        String location = keyStoreElt.getFirstChildWithName(new QName("Location")).getText();
        String type = keyStoreElt.getFirstChildWithName(new QName("Type")).getText();
        String storePassword = keyStoreElt.getFirstChildWithName(new QName("Password")).getText();
        String keyPassword = keyStoreElt.getFirstChildWithName(new QName("KeyPassword")).getText();

        FileInputStream fis = null;
        try {// w ww.  jav  a  2s  .  c o  m
            KeyStore keyStore = KeyStore.getInstance(type);
            fis = new FileInputStream(location);
            if (log.isInfoEnabled()) {
                log.info(name + " Loading Identity Keystore from : " + location);
            }

            keyStore.load(fis, storePassword.toCharArray());
            KeyManagerFactory kmfactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmfactory.init(keyStore, keyPassword.toCharArray());
            keymanagers = kmfactory.getKeyManagers();

        } catch (GeneralSecurityException gse) {
            log.error(name + " Error loading Keystore : " + location, gse);
            throw new AxisFault("Error loading Keystore : " + location, gse);
        } catch (IOException ioe) {
            log.error(name + " Error opening Keystore : " + location, ioe);
            throw new AxisFault("Error opening Keystore : " + location, ioe);
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException ignore) {
                }
            }
        }
    }

    if (trustStoreElt != null) {
        if (novalidatecert && log.isWarnEnabled()) {
            log.warn(name + " Ignoring novalidatecert parameter since a truststore has been specified");
        }

        String location = trustStoreElt.getFirstChildWithName(new QName("Location")).getText();
        String type = trustStoreElt.getFirstChildWithName(new QName("Type")).getText();
        String storePassword = trustStoreElt.getFirstChildWithName(new QName("Password")).getText();

        FileInputStream fis = null;
        try {
            KeyStore trustStore = KeyStore.getInstance(type);
            fis = new FileInputStream(location);
            if (log.isInfoEnabled()) {
                log.info(name + " Loading Trust Keystore from : " + location);
            }

            trustStore.load(fis, storePassword.toCharArray());
            TrustManagerFactory trustManagerfactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerfactory.init(trustStore);
            trustManagers = trustManagerfactory.getTrustManagers();

        } catch (GeneralSecurityException gse) {
            log.error(name + " Error loading Key store : " + location, gse);
            throw new AxisFault("Error loading Key store : " + location, gse);
        } catch (IOException ioe) {
            log.error(name + " Error opening Key store : " + location, ioe);
            throw new AxisFault("Error opening Key store : " + location, ioe);
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException ignore) {
                }
            }
        }
    } else if (novalidatecert) {
        if (log.isWarnEnabled()) {
            log.warn(name + " Server certificate validation (trust) has been disabled. "
                    + "DO NOT USE IN PRODUCTION!");
        }
        trustManagers = new TrustManager[] { new NoValidateCertTrustManager() };
    }

    try {
        final Parameter sslpParameter = transportOut.getParameter("SSLProtocol");
        final String sslProtocol = sslpParameter != null ? sslpParameter.getValue().toString() : "TLS";
        SSLContext sslcontext = SSLContext.getInstance(sslProtocol);
        sslcontext.init(keymanagers, trustManagers, null);
        return sslcontext;

    } catch (GeneralSecurityException gse) {
        log.error(name + " Unable to create SSL context with the given configuration", gse);
        throw new AxisFault("Unable to create SSL context with the given configuration", gse);
    }
}

From source file:org.whispersystems.textsecure.push.PushServiceSocket.java

private TrustManager[] initializeTrustManager(TrustStore trustStore) {
    try {//from  ww  w .jav  a2 s. c  o m
        InputStream keyStoreInputStream = trustStore.getKeyStoreInputStream();
        KeyStore keyStore = KeyStore.getInstance("BKS");

        keyStore.load(keyStoreInputStream, trustStore.getKeyStorePassword().toCharArray());

        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("X509");
        trustManagerFactory.init(keyStore);

        return BlacklistingTrustManager.createFor(trustManagerFactory.getTrustManagers());
    } catch (KeyStoreException kse) {
        throw new AssertionError(kse);
    } catch (CertificateException e) {
        throw new AssertionError(e);
    } catch (NoSuchAlgorithmException e) {
        throw new AssertionError(e);
    } catch (IOException ioe) {
        throw new AssertionError(ioe);
    }
}

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

/**
 * This method sets up the security.//from  ww w.  j  a va2 s.  c  om
 * 
 * @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:com.alliander.osgp.shared.usermanagement.UserManagementClient.java

/**
 * Construct a UserManagementClient instance.
 *
 * @param keystoreLocation// ww  w  .ja  va  2 s .c  o m
 *            The location of the key store.
 * @param keystorePassword
 *            The password for the key store.
 * @param keystoreType
 *            The type of the key store.
 * @param baseAddress
 *            The base address or URL for the UserManagementClient.
 *
 * @throws UserManagementClientException
 *             In case the construction fails, a
 *             UserManagmentClientException will be thrown.
 */
public UserManagementClient(final String keystoreLocation, final String keystorePassword,
        final String keystoreType, final String baseAddress) throws UserManagementClientException {

    InputStream stream = null;
    boolean isClosed = false;
    Exception exception = null;

    try {
        // Create the KeyStore.
        final KeyStore keystore = KeyStore.getInstance(keystoreType.toUpperCase());

        stream = new FileInputStream(keystoreLocation);
        keystore.load(stream, keystorePassword.toCharArray());

        // Create TrustManagerFactory and initialize it using the KeyStore.
        final TrustManagerFactory tmf = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(keystore);

        // Create Apache CXF WebClient with JSON provider.
        final List<Object> providers = new ArrayList<Object>();
        providers.add(new JacksonJaxbJsonProvider());

        this.webClient = WebClient.create(baseAddress, providers);
        if (this.webClient == null) {
            throw new UserManagementClientException("webclient is null");
        }

        // Set up the HTTP Conduit to use the TrustManagers.
        final ClientConfiguration config = WebClient.getConfig(this.webClient);
        final HTTPConduit conduit = config.getHttpConduit();

        conduit.setTlsClientParameters(new TLSClientParameters());
        conduit.getTlsClientParameters().setTrustManagers(tmf.getTrustManagers());
    } catch (final Exception e) {
        LOGGER.error(CONSTRUCTION_FAILED, e);
        throw new UserManagementClientException(CONSTRUCTION_FAILED, e);
    } finally {
        try {
            stream.close();
            isClosed = true;
        } catch (final Exception streamCloseException) {
            LOGGER.error(CONSTRUCTION_FAILED, streamCloseException);
            exception = streamCloseException;
        }
    }

    if (!isClosed) {
        throw new UserManagementClientException(CONSTRUCTION_FAILED, exception);
    }
}