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:davmail.http.DavGatewaySSLProtocolSocketFactory.java

private SSLContext createSSLContext() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException,
        KeyManagementException, KeyStoreException {
    // PKCS11 client certificate settings
    String pkcs11Library = Settings.getProperty("davmail.ssl.pkcs11Library");

    String clientKeystoreType = Settings.getProperty("davmail.ssl.clientKeystoreType");
    // set default keystore type
    if (clientKeystoreType == null || clientKeystoreType.length() == 0) {
        clientKeystoreType = "PKCS11";
    }//from  w ww. j  av  a 2s. c o  m

    if (pkcs11Library != null && pkcs11Library.length() > 0 && "PKCS11".equals(clientKeystoreType)) {
        StringBuilder pkcs11Buffer = new StringBuilder();
        pkcs11Buffer.append("name=DavMail\n");
        pkcs11Buffer.append("library=").append(pkcs11Library).append('\n');
        String pkcs11Config = Settings.getProperty("davmail.ssl.pkcs11Config");
        if (pkcs11Config != null && pkcs11Config.length() > 0) {
            pkcs11Buffer.append(pkcs11Config).append('\n');
        }
        SunPKCS11ProviderHandler.registerProvider(pkcs11Buffer.toString());
    }

    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(/*KeyManagerFactory.getDefaultAlgorithm()*/"NewSunX509");

    ArrayList<KeyStore.Builder> keyStoreBuilders = new ArrayList<KeyStore.Builder>();
    // PKCS11 (smartcard) keystore with password callback
    KeyStore.Builder scBuilder = KeyStore.Builder.newInstance("PKCS11", null, getProtectionParameter(null));
    keyStoreBuilders.add(scBuilder);

    String clientKeystoreFile = Settings.getProperty("davmail.ssl.clientKeystoreFile");
    String clientKeystorePass = Settings.getProperty("davmail.ssl.clientKeystorePass");
    if (clientKeystoreFile != null && clientKeystoreFile.length() > 0
            && ("PKCS12".equals(clientKeystoreType) || "JKS".equals(clientKeystoreType))) {
        // PKCS12 file based keystore
        KeyStore.Builder fsBuilder = KeyStore.Builder.newInstance(clientKeystoreType, null,
                new File(clientKeystoreFile), getProtectionParameter(clientKeystorePass));
        keyStoreBuilders.add(fsBuilder);
    }

    ManagerFactoryParameters keyStoreBuilderParameters = new KeyStoreBuilderParameters(keyStoreBuilders);
    keyManagerFactory.init(keyStoreBuilderParameters);

    // Get a list of key managers
    KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();

    // Walk through the key managers and replace all X509 Key Managers with
    // a specialized wrapped DavMail X509 Key Manager
    for (int i = 0; i < keyManagers.length; i++) {
        KeyManager keyManager = keyManagers[i];
        if (keyManager instanceof X509KeyManager) {
            keyManagers[i] = new DavMailX509KeyManager((X509KeyManager) keyManager);
        }
    }

    SSLContext context = SSLContext.getInstance("SSL");
    context.init(keyManagers, new TrustManager[] { new DavGatewayX509TrustManager() }, null);
    return context;
}

From source file:org.apache.nifi.cluster.coordination.http.replication.okhttp.OkHttpReplicationClient.java

private Tuple<SSLSocketFactory, X509TrustManager> createSslSocketFactory(final NiFiProperties properties) {
    final SSLContext sslContext = SslContextFactory.createSslContext(properties);

    if (sslContext == null) {
        return null;
    }/*from  www.  j  a  va 2  s . c  o m*/

    try {
        final KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("X509");

        // initialize the KeyManager array to null and we will overwrite later if a keystore is loaded
        KeyManager[] keyManagers = null;

        // we will only initialize the keystore if properties have been supplied by the SSLContextService
        final String keystoreLocation = properties.getProperty(NiFiProperties.SECURITY_KEYSTORE);
        final String keystorePass = properties.getProperty(NiFiProperties.SECURITY_KEYSTORE_PASSWD);
        final String keystoreType = properties.getProperty(NiFiProperties.SECURITY_KEYSTORE_TYPE);

        // prepare the keystore
        final KeyStore keyStore = KeyStore.getInstance(keystoreType);

        try (FileInputStream keyStoreStream = new FileInputStream(keystoreLocation)) {
            keyStore.load(keyStoreStream, keystorePass.toCharArray());
        }

        keyManagerFactory.init(keyStore, keystorePass.toCharArray());
        keyManagers = keyManagerFactory.getKeyManagers();

        // we will only initialize the truststure if properties have been supplied by the SSLContextService
        // load truststore
        final String truststoreLocation = properties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE);
        final String truststorePass = properties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_PASSWD);
        final String truststoreType = properties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_TYPE);

        KeyStore truststore = KeyStore.getInstance(truststoreType);
        truststore.load(new FileInputStream(truststoreLocation), truststorePass.toCharArray());
        trustManagerFactory.init(truststore);

        // TrustManagerFactory.getTrustManagers returns a trust manager for each type of trust material. Since we are getting a trust manager factory that uses "X509"
        // as it's trust management algorithm, we are able to grab the first (and thus the most preferred) and use it as our x509 Trust Manager
        //
        // https://docs.oracle.com/javase/8/docs/api/javax/net/ssl/TrustManagerFactory.html#getTrustManagers--
        final X509TrustManager x509TrustManager;
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
        if (trustManagers[0] != null) {
            x509TrustManager = (X509TrustManager) trustManagers[0];
        } else {
            throw new IllegalStateException("List of trust managers is null");
        }

        // if keystore properties were not supplied, the keyManagers array will be null
        sslContext.init(keyManagers, trustManagerFactory.getTrustManagers(), null);

        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        return new Tuple<>(sslSocketFactory, x509TrustManager);
    } catch (final Exception e) {
        throw new RuntimeException(
                "Failed to create SSL Socket Factory for replicating requests across the cluster");
    }
}

From source file:org.wso2.carbon.device.mgt.core.geo.service.GeoLocationProviderServiceImpl.java

/**
 * Initializes the SSL Context/*from ww w . j  a  v  a2  s. co m*/
 */
private SSLContext initSSLConnection(String tenantAdminUser)
        throws NoSuchAlgorithmException, UnrecoverableKeyException, KeyStoreException, KeyManagementException,
        IOException, CertificateException {
    String keyStorePassword = ServerConfiguration.getInstance().getFirstProperty("Security.KeyStore.Password");
    String trustStorePassword = ServerConfiguration.getInstance()
            .getFirstProperty("Security.TrustStore.Password");
    String keyStoreLocation = ServerConfiguration.getInstance().getFirstProperty("Security.KeyStore.Location");
    String trustStoreLocation = ServerConfiguration.getInstance()
            .getFirstProperty("Security.TrustStore.Location");

    //Call to load the keystore.
    KeyStore keyStore = loadKeyStore(keyStoreLocation, keyStorePassword.toCharArray());
    //Call to load the TrustStore.
    KeyStore trustStore = loadTrustStore(trustStoreLocation, trustStorePassword.toCharArray());

    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KEY_MANAGER_TYPE);
    keyManagerFactory.init(keyStore, keyStorePassword.toCharArray());
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TRUST_MANAGER_TYPE);
    trustManagerFactory.init(trustStore);

    // Create and initialize SSLContext for HTTPS communication

    SSLContext sslContext = SSLContext.getInstance(SSLV3);
    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
    SSLContext.setDefault(sslContext);
    return sslContext;
}

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

/**
 * This method is to confgiure KeyStore and Truststore for Grants.Gov webservice client
 * @param tlsConfig/*from w  w w  . jav  a  2s  .c  o 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(s2sCertificateReader.getJksType());
            Certificate[] certificates = keyStore.getCertificateChain(alias);
            Key key = keyStore.getKey(alias,
                    s2SUtilService.getProperty(s2sCertificateReader.getKeyStorePassword()).toCharArray());
            keyStoreAlias.load(null, null);
            keyStoreAlias.setKeyEntry(alias, key,
                    s2SUtilService.getProperty(s2sCertificateReader.getKeyStorePassword()).toCharArray(),
                    certificates);
            keyManagerFactory.init(keyStoreAlias,
                    s2SUtilService.getProperty(s2sCertificateReader.getKeyStorePassword()).toCharArray());
        } else {
            keyManagerFactory.init(keyStore,
                    s2SUtilService.getProperty(s2sCertificateReader.getKeyStorePassword()).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:org.kuali.coeus.propdev.impl.s2s.connect.S2SConnectorServiceBase.java

/**
 * This method is to confgiure KeyStore and Truststore for Grants.Gov webservice client
 * @param tlsConfig//w w w.  j a v a 2s . c  o  m
 * @param alias
 * @param mulitCampusEnabled
 * @throws S2sCommunicationException
 */
protected void configureKeyStoreAndTrustStore(TLSClientParameters tlsConfig, String alias,
        boolean mulitCampusEnabled) throws S2sCommunicationException {
    KeyStore keyStore = s2sCertificateReader.getKeyStore();
    KeyManagerFactory keyManagerFactory;
    try {
        keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        if (alias != null && mulitCampusEnabled) {
            KeyStore keyStoreAlias;
            keyStoreAlias = KeyStore.getInstance(s2sCertificateReader.getJksType());
            Certificate[] certificates = keyStore.getCertificateChain(alias);
            Key key = keyStore.getKey(alias, s2SConfigurationService
                    .getValueAsString(s2sCertificateReader.getKeyStorePassword()).toCharArray());
            keyStoreAlias.load(null, null);
            keyStoreAlias.setKeyEntry(
                    alias, key, s2SConfigurationService
                            .getValueAsString(s2sCertificateReader.getKeyStorePassword()).toCharArray(),
                    certificates);
            keyManagerFactory.init(keyStoreAlias, s2SConfigurationService
                    .getValueAsString(s2sCertificateReader.getKeyStorePassword()).toCharArray());
        } else {
            keyManagerFactory.init(keyStore, s2SConfigurationService
                    .getValueAsString(s2sCertificateReader.getKeyStorePassword()).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 | KeyStoreException | UnrecoverableKeyException | CertificateException
            | IOException e) {
        LOG.error(e.getMessage(), e);
        throw new S2sCommunicationException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    }
}

From source file:com.sat.vcse.automation.utils.http.HttpClient.java

private SSLContext getSSLContext() {

    final String METHOD_NAME = "getSSLContext(): ";
    SSLContext sslContext = null;

    try {//from  w w w  .  j  ava 2  s  .  c  om
        //Get the TrustManager based on client truststore file presence or no
        final TrustManager[] trustManager = getTrustManagers();
        // Configure the SSLContext object with the defined cryptoProtocol 
        sslContext = SSLContext.getInstance(this.cryptoProtocol);

        if (this.isClientAuthEnabled) {
            // Load the Client Keystore
            final KeyManagerFactory kmf = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            final KeyStore clientKeystore = KeyStore.getInstance(KeyStore.getDefaultType());

            InputStream keystoreis = null;
            //see if the file is present otherwise read from class path
            File keStoreFile = new File(this.keystore);
            if (keStoreFile.exists()) {
                keystoreis = new FileInputStream(keStoreFile);
            } else {
                LogHandler.warn("File not found, so trying to read it from class path now");
                keystoreis = HttpClient.class.getResourceAsStream(this.keystore);
            }

            clientKeystore.load(keystoreis, this.keystorePasswd.toCharArray());
            kmf.init(clientKeystore, this.keystorePasswd.toCharArray());
            // Configure the SSLContext object with the Keystore, Truststore and random data 
            sslContext.init(kmf.getKeyManagers(), trustManager, new SecureRandom());

        } else {
            // Configure the SSLContext object with the only a Truststore and random data 
            sslContext.init(null, trustManager, new SecureRandom());
        }

    } catch (Exception exp) {
        LogHandler.error(CLASS_NAME + METHOD_NAME + exp.getMessage());
        throw new CoreRuntimeException(exp, CLASS_NAME + METHOD_NAME + exp.getMessage());
    }

    return sslContext;
}

From source file:de.betterform.connector.http.ssl.BetterFORMKeyStoreManager.java

private X509KeyManager getCustomX509KeyManager(final URL url, final String password)
        throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException,
        UnrecoverableKeyException {
    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    if (url == null) {
        throw new IllegalArgumentException("BetterFORMKeyStoreManager: Keystore url may not be null");
    }//  w  w w. j  a  va 2 s.  c  o m

    LOGGER.debug("BetterFORMKeyStoreManager: initializing custom key store");
    KeyStore customKeystore = KeyStore.getInstance(KeyStore.getDefaultType());
    InputStream is = null;
    try {
        is = url.openStream();
        customKeystore.load(is, password != null ? password.toCharArray() : null);
    } finally {
        if (is != null)
            is.close();
    }

    if (LOGGER.isTraceEnabled()) {
        Enumeration aliases = customKeystore.aliases();
        while (aliases.hasMoreElements()) {
            String alias = (String) aliases.nextElement();
            LOGGER.trace("Trusted certificate '" + alias + "':");
            Certificate trustedcert = customKeystore.getCertificate(alias);
            if (trustedcert != null && trustedcert instanceof X509Certificate) {
                X509Certificate cert = (X509Certificate) trustedcert;
                LOGGER.trace("  Subject DN: " + cert.getSubjectDN());
                LOGGER.trace("  Signature Algorithm: " + cert.getSigAlgName());
                LOGGER.trace("  Valid from: " + cert.getNotBefore());
                LOGGER.trace("  Valid until: " + cert.getNotAfter());
                LOGGER.trace("  Issuer: " + cert.getIssuerDN());
            }
        }
    }
    keyManagerFactory.init(customKeystore, password.toCharArray());

    KeyManager[] customX509KeyManagers = keyManagerFactory.getKeyManagers();
    if (customX509KeyManagers != null && customX509KeyManagers.length > 0) {
        for (int i = 0; i < customX509KeyManagers.length; i++) {
            if (customX509KeyManagers[i] instanceof X509KeyManager) {
                return (X509KeyManager) customX509KeyManagers[i];
            }
        }
    }

    return null;
}

From source file:ch.admin.vbs.cube.core.webservice.CubeSSLSocketFactory.java

/**
 * Create a new SSL socket factory./*from   w  w  w .j a  v  a  2  s  . c  o m*/
 * 
 * @param keyStoreBuilder
 *            the key store builder
 * @param trustStore
 *            the trust store
 * @param checkRevocation
 *            <code>true</code> if certificate revocations should be
 *            checked, else <code>false</code>
 * @throws WebServiceException
 *             if the creation failed
 */
public static SSLSocketFactory newSSLSocketFactory(KeyStore.Builder keyStoreBuilder, KeyStore trustStore,
        boolean checkRevocation) throws WebServiceException {
    KeyManagerFactory keyManagerFactory;
    try {
        keyManagerFactory = KeyManagerFactory.getInstance("NewSunX509");
    } catch (NoSuchAlgorithmException e) {
        String message = "Unable to create key manager factory";
        LOG.error(message + ": " + e.getMessage());
        throw new WebServiceException(message, e);
    }
    KeyStoreBuilderParameters keyStoreBuilderParameters = new KeyStoreBuilderParameters(keyStoreBuilder);
    try {
        keyManagerFactory.init(keyStoreBuilderParameters);
    } catch (InvalidAlgorithmParameterException e) {
        String message = "Unable to initialize key manager factory";
        LOG.error(message + ": " + e.getMessage());
        throw new WebServiceException(message, e);
    }
    TrustManagerFactory trustManagerFactory;
    try {
        trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    } catch (NoSuchAlgorithmException e) {
        String message = "Unable to create trust manager factory";
        LOG.error(message + ": " + e.getMessage());
        throw new WebServiceException(message, e);
    }
    PKIXBuilderParameters pkixBuilderParameters;
    try {
        pkixBuilderParameters = new PKIXBuilderParameters(trustStore, null);
    } catch (KeyStoreException e) {
        String message = "The trust store is not initialized";
        LOG.error(message + ": " + e.getMessage());
        throw new WebServiceException(message, e);
    } catch (InvalidAlgorithmParameterException e) {
        String message = "The trust store does not contain any trusted certificate";
        LOG.error(message + ": " + e.getMessage());
        throw new WebServiceException(message, e);
    } catch (NullPointerException e) {
        String message = "The trust store is null";
        LOG.error(message + ": " + e.getMessage());
        throw new WebServiceException(message, e);
    }
    pkixBuilderParameters.setRevocationEnabled(checkRevocation);
    CertPathTrustManagerParameters certPathTrustManagerParameters = new CertPathTrustManagerParameters(
            pkixBuilderParameters);
    try {
        trustManagerFactory.init(certPathTrustManagerParameters);
    } catch (InvalidAlgorithmParameterException e) {
        String message = "Unable to initialize trust manager factory";
        LOG.error(message + ": " + e.getMessage());
        throw new WebServiceException(message, e);
    }
    SSLContext sslContext;
    try {
        sslContext = SSLContext.getInstance("TLS");
    } catch (NoSuchAlgorithmException e) {
        String message = "Unable to create SSL context";
        LOG.error(message + ": " + e.getMessage());
        throw new WebServiceException(message, e);
    }
    try {
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
    } catch (KeyManagementException e) {
        String message = "Unable to initialize SSL context";
        LOG.error(message + ": " + e.getMessage());
        throw new WebServiceException(message, e);
    }
    SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
    return sslSocketFactory;
}

From source file:davmail.util.ClientCertificateTest.java

private SSLContext createSSLContext()
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, KeyManagementException,
        KeyStoreException, IOException, CertificateException, UnrecoverableKeyException {
    // PKCS11 client certificate settings
    String pkcs11Library = Settings.getProperty("davmail.ssl.pkcs11Library");

    String clientKeystoreType = Settings.getProperty("davmail.ssl.clientKeystoreType");
    // set default keystore type
    if (clientKeystoreType == null || clientKeystoreType.length() == 0) {
        clientKeystoreType = "PKCS11";
    }//from   w  w w  . j av  a 2 s. co m

    if (pkcs11Library != null && pkcs11Library.length() > 0 && "PKCS11".equals(clientKeystoreType)) {
        StringBuilder pkcs11Buffer = new StringBuilder();
        pkcs11Buffer.append("name=DavMail\n");
        pkcs11Buffer.append("library=").append(pkcs11Library).append('\n');
        String pkcs11Config = Settings.getProperty("davmail.ssl.pkcs11Config");
        if (pkcs11Config != null && pkcs11Config.length() > 0) {
            pkcs11Buffer.append(pkcs11Config).append('\n');
        }
        SunPKCS11ProviderHandler.registerProvider(pkcs11Buffer.toString());
    }
    String algorithm = KeyManagerFactory.getDefaultAlgorithm();
    if ("SunX509".equals(algorithm)) {
        algorithm = "NewSunX509";
    } else if ("IbmX509".equals(algorithm)) {
        algorithm = "NewIbmX509";
    }
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(algorithm);

    ArrayList<KeyStore.Builder> keyStoreBuilders = new ArrayList<KeyStore.Builder>();
    // PKCS11 (smartcard) keystore with password callback
    KeyStore.Builder scBuilder = KeyStore.Builder.newInstance("PKCS11", null, getProtectionParameter(null));
    //keyStoreBuilders.add(scBuilder);

    String clientKeystoreFile = Settings.getProperty("davmail.ssl.clientKeystoreFile");
    String clientKeystorePass = Settings.getProperty("davmail.ssl.clientKeystorePass");
    if (clientKeystoreFile != null && clientKeystoreFile.length() > 0
            && ("PKCS12".equals(clientKeystoreType) || "JKS".equals(clientKeystoreType))) {
        // PKCS12 file based keystore
        KeyStore.Builder fsBuilder = KeyStore.Builder.newInstance(clientKeystoreType, null,
                new File(clientKeystoreFile), getProtectionParameter(clientKeystorePass));
        keyStoreBuilders.add(fsBuilder);
    }
    System.setProperty("javax.net.debug", "ssl,handshake");
    //try {
    Provider sunMSCAPI = new sun.security.mscapi.SunMSCAPI();
    //Security.insertProviderAt(sunMSCAPI, 1);
    KeyStore keyStore = KeyStore.getInstance("Windows-MY", sunMSCAPI);

    keyStore.load(null, null);

    keyStoreBuilders.add(KeyStore.Builder.newInstance(keyStore, new KeyStore.PasswordProtection(null)));

    /*} catch (IOException e) {
    e.printStackTrace();
    } catch (CertificateException e) {
    e.printStackTrace();
    }*/

    ManagerFactoryParameters keyStoreBuilderParameters = new KeyStoreBuilderParameters(keyStoreBuilders);
    keyManagerFactory.init(keyStoreBuilderParameters);
    //keyManagerFactory.init(keyStore, null);

    // Get a list of key managers
    KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();

    // Walk through the key managers and replace all X509 Key Managers with
    // a specialized wrapped DavMail X509 Key Manager
    for (int i = 0; i < keyManagers.length; i++) {
        KeyManager keyManager = keyManagers[i];
        if (keyManager instanceof X509KeyManager) {
            keyManagers[i] = new DavMailX509KeyManager((X509KeyManager) keyManager);
        }
    }

    //keyManagers = new KeyManager[]{new DavMailX509KeyManager(new X509KeyManagerImpl())}

    SSLContext context = SSLContext.getInstance("TLS");
    context.init(keyManagers, new TrustManager[] { new DavGatewayX509TrustManager() }, null);
    return context;
}