Example usage for javax.net.ssl KeyManagerFactory getDefaultAlgorithm

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

Introduction

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

Prototype

public static final String getDefaultAlgorithm() 

Source Link

Document

Obtains the default KeyManagerFactory algorithm name.

Usage

From source file:org.springframework.vault.config.ClientHttpRequestFactoryFactory.java

private static KeyManagerFactory createKeyManagerFactory(Resource keystoreFile, String storePassword)
        throws GeneralSecurityException, IOException {

    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());

    loadKeyStore(keystoreFile, storePassword, keyStore);

    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore,//from w  ww. java  2s  .c  om
            StringUtils.hasText(storePassword) ? storePassword.toCharArray() : new char[0]);

    return keyManagerFactory;
}

From source file:ddf.catalog.source.opensearch.SecureRemoteConnectionImpl.java

/**
 * Creates a new SSLSocketFactory from a truststore and keystore. This is used during SSL
 * communications with the server./*www .j  av a 2s .  co m*/
 * 
 * @param trustStoreLoc
 *            File path to the truststore.
 * @param trustStorePass
 *            Password to the truststore.
 * @param keyStoreLoc
 *            File path to the keystore.
 * @param keyStorePass
 *            Password to the keystore.
 * @return new SSLSocketFactory instance containing the trust and key stores.
 * @throws KeyStoreException
 * @throws IOException
 * @throws CertificateException
 * @throws NoSuchAlgorithmException
 * @throws UnrecoverableKeyException
 * @throws KeyManagementException
 */
public SSLSocketFactory createSocket(String trustStoreLoc, String trustStorePass, String keyStoreLoc,
        String keyStorePass) throws KeyStoreException, NoSuchAlgorithmException, CertificateException,
        IOException, UnrecoverableKeyException, KeyManagementException {
    String methodName = "createSocket";
    LOGGER.debug("ENTERING: " + methodName);

    LOGGER.debug("trustStoreLoc = " + trustStoreLoc);
    FileInputStream trustFIS = new FileInputStream(trustStoreLoc);
    LOGGER.debug("keyStoreLoc = " + keyStoreLoc);
    FileInputStream keyFIS = new FileInputStream(keyStoreLoc);

    // truststore stuff
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    try {
        LOGGER.debug("Loading trustStore");
        trustStore.load(trustFIS, trustStorePass.toCharArray());
    } finally {
        IOUtils.closeQuietly(trustFIS);
    }

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(trustStore);
    LOGGER.debug("trust manager factory initialized");

    // keystore stuff
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    try {
        LOGGER.debug("Loading keyStore");
        keyStore.load(keyFIS, keyStorePass.toCharArray());
    } finally {
        IOUtils.closeQuietly(keyFIS);
    }
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(keyStore, keyStorePass.toCharArray());
    LOGGER.debug("key manager factory initialized");

    // ssl context
    SSLContext sslCtx = SSLContext.getInstance("TLS");
    sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

    LOGGER.debug("EXITING: " + methodName);

    return sslCtx.getSocketFactory();
}

From source file:org.apache.nifi.elasticsearch.ElasticSearchClientServiceImpl.java

private SSLContext buildSslContext(SSLContextService sslService) throws IOException, CertificateException,
        NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, KeyManagementException {
    KeyStore keyStore = KeyStore.getInstance(sslService.getKeyStoreType());
    KeyStore trustStore = KeyStore.getInstance("JKS");

    try (final InputStream is = new FileInputStream(sslService.getKeyStoreFile())) {
        keyStore.load(is, sslService.getKeyStorePassword().toCharArray());
    }//from   ww  w  .j  ava 2 s.co m

    try (final InputStream is = new FileInputStream(sslService.getTrustStoreFile())) {
        trustStore.load(is, sslService.getTrustStorePassword().toCharArray());
    }

    final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(keyStore, sslService.getKeyStorePassword().toCharArray());
    final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(keyStore);
    SSLContext context1 = SSLContext.getInstance(sslService.getSslAlgorithm());
    context1.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());
    return context1;
}

From source file:gov.niem.ws.util.SecurityUtil.java

public static KeyManager[] createKeyManagers(KeyPair clientKey, X509Certificate clientCert)
        throws GeneralSecurityException, IOException {
    // Create a new empty key store.
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(null);/* ww  w . j  a v a2  s .com*/

    Certificate[] chain = { clientCert };

    // The KeyStore requires a password for key entries.
    char[] password = { ' ' };

    // Since we never write out the key store, we don't bother protecting
    // the key.
    ks.setEntry("client-key", new KeyStore.PrivateKeyEntry(clientKey.getPrivate(), chain),
            new KeyStore.PasswordProtection(password));

    // Shove the key store in a KeyManager.
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(ks, password);
    return kmf.getKeyManagers();
}

From source file:davmail.util.ClientCertificateTest.java

public void testClientSocket() throws NoSuchAlgorithmException, KeyStoreException, IOException,
        CertificateException, KeyManagementException, UnrecoverableKeyException {

    //System.setProperty("javax.net.ssl.trustStoreProvider", "SunMSCAPI");
    //System.setProperty("javax.net.ssl.trustStoreType", "Windows-ROOT");
    System.setProperty("javax.net.ssl.trustStore", "cacerts");
    System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
    System.setProperty("javax.net.ssl.trustStoreType", "JKS");

    String algorithm = KeyManagerFactory.getDefaultAlgorithm();
    if ("SunX509".equals(algorithm)) {
        algorithm = "NewSunX509";
    } else if ("IbmX509".equals(algorithm)) {
        algorithm = "NewIbmX509";
    }//w w  w .  jav a  2s .  co m

    Provider sunMSCAPI = new sun.security.mscapi.SunMSCAPI();
    //Security.insertProviderAt(sunMSCAPI, 1);
    KeyStore keyStore = KeyStore.getInstance("Windows-MY", sunMSCAPI);
    keyStore.load(null, null);

    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(algorithm);
    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);
        }
    }

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(keyManagers, null, null);
    SSLSocketFactory sockFactory = sslContext.getSocketFactory();
    SSLSocket sslSock = (SSLSocket) sockFactory.createSocket("localhost", 443);
    sslSock.startHandshake();

}

From source file:org.soyatec.windowsazure.internal.util.ssl.SslUtil.java

private static KeyManager[] createKeyManagers(final KeyStore keystore, final String password) throws Exception {
    if (keystore == null) {
        throw new IllegalArgumentException("Keystore may not be null");
    }/*w w w . jav a 2s.co m*/
    KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmfactory.init(keystore, password != null ? password.toCharArray() : null);
    return kmfactory.getKeyManagers();
}

From source file:edu.washington.iam.tools.IamConnectionManager.java

protected void initManagers() {

    // trust managers
    /**/*from  w w  w .  j av a 2s.  c om*/
           try {
               TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            
               X509Certificate cert = null;
               if (caFilename!=null) cert = readCertificate(caFilename);
               log.debug("init trust mgr " + cert);
               trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
               trustStore.load(null, null);
               trustStore.setCertificateEntry("CACERT", cert);
               tmf.init(trustStore);
               trustManagers = tmf.getTrustManagers();
           } catch (Exception e) {
               log.error("cacert error: " + e);
           }
     **/
    trustManagers = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(X509Certificate[] certs, String authType) {
            return;
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) {
            return;
        }
    } };

    // key managers
    if (certFilename != null && keyFilename != null) {
        try {
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(null, null);

            X509Certificate cert = readCertificate(certFilename);
            PKCS1 pkcs = new PKCS1();
            PrivateKey key = pkcs.readKey(keyFilename);

            X509Certificate[] chain = new X509Certificate[1];
            chain[0] = cert;
            keyStore.setKeyEntry("CERT", (Key) key, "pw".toCharArray(), chain);

            kmf.init(keyStore, "pw".toCharArray());
            keyManagers = kmf.getKeyManagers();
        } catch (Exception e) {
            log.error("cert/key error: " + e);
        }
    }

}

From source file:io.dropwizard.revolver.http.RevolverHttpClientFactory.java

private static SSLContext getSSLContext(final String keyStorePath, final String keyStorePassword)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException,
        KeyManagementException, UnrecoverableKeyException {
    final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    try (InputStream instream = RevolverHttpClientFactory.class.getClassLoader()
            .getResourceAsStream(keyStorePath)) {
        keyStore.load(instream, keyStorePassword.toCharArray());
    }//  ww  w .  j  av a2 s.co  m
    final TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(keyStore);
    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, keyStorePassword.toCharArray());
    final SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(),
            new SecureRandom());
    return sslContext;
}

From source file:learn.encryption.ssl.SSLContext_Https.java

/**
 * @description javaSSLContext/*from w w w.j a va2  s .c  o m*/
 * @description https?, SSLContext (NoHttp?SecureRandombug)
 * @description client.ks?server
 * @description ??
 * @description ????getSSLContext2()
 */
//@SuppressLint("TrulyRandom")
public static SSLContext getSSLContext() {
    SSLContext sslContext = null;
    try {
        sslContext = SSLContext.getInstance("TLS");
        // ??, ??assets
        InputStream inputStream = new FileInputStream(new File("D:\\tomcatcert\\server.ks"));
        //App.getInstance().getAssets().open("srca.cer");

        // ??
        CertificateFactory cerFactory = CertificateFactory.getInstance("X.509");

        // ?KeyStore
        KeyStore keyStore = KeyStore.getInstance("jks");
        keyStore.load(inputStream, "123456".toCharArray());
        //Certificate cer = cerFactory.generateCertificate(inputStream);
        Certificate cer = keyStore.getCertificate("clientKey");
        keyStore.setCertificateEntry("trust", cer);

        // KeyStorekeyManagerFactory
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, "123456".toCharArray());

        // KeyStoreTrustManagerFactory
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);

        // ?SSLContext
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(),
                new SecureRandom());
    } catch (Exception e) {
        e.printStackTrace();
    }

    return sslContext;
}

From source file:it.govpay.core.utils.client.BasicClient.java

private BasicClient(String bundleKey, Connettore connettore) throws ClientException {

    if (connettore == null) {
        throw new ClientException("Connettore non configurato");
    }//from ww  w  .  ja v  a  2s .  co m

    try {
        this.url = new URL(connettore.getUrl());
    } catch (Exception e) {
        throw new ClientException("La URL del connettore " + errMsg + " non e' valida: " + e);
    }
    sslContext = sslContexts.get(bundleKey);

    if (connettore.getTipoAutenticazione().equals(EnumAuthType.SSL)) {
        isSslEnabled = true;
        if (sslContext == null) {
            try {
                FileInputStream finKeyStore = null;
                FileInputStream finTrustStore = null;

                KeyManager[] km = null;
                TrustManager[] tm = null;

                // Autenticazione CLIENT
                if (connettore.getTipoSsl().equals(EnumSslType.CLIENT)) {

                    if (connettore.getSslKsType() == null || connettore.getSslKsLocation() == null
                            || connettore.getSslKsPasswd() == null || connettore.getSslPKeyPasswd() == null)
                        throw new ClientException(
                                "Configurazione SSL Client del connettore " + errMsg + " incompleta.");

                    KeyStore keystore = KeyStore.getInstance(connettore.getSslKsType()); // JKS,PKCS12,jceks,bks,uber,gkr
                    finKeyStore = new FileInputStream(connettore.getSslKsLocation());
                    keystore.load(finKeyStore, connettore.getSslKsPasswd().toCharArray());
                    KeyManagerFactory keyManagerFactory = KeyManagerFactory
                            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
                    keyManagerFactory.init(keystore, connettore.getSslPKeyPasswd().toCharArray());
                    km = keyManagerFactory.getKeyManagers();
                }

                if (connettore.getSslTsType() == null || connettore.getSslTsLocation() == null
                        || connettore.getSslTsPasswd() == null || connettore.getSslType() == null)
                    throw new ClientException(
                            "Configurazione SSL Server del connettore " + errMsg + " incompleta.");

                // Autenticazione SERVER
                KeyStore truststore = KeyStore.getInstance(connettore.getSslTsType()); // JKS,PKCS12,jceks,bks,uber,gkr
                finTrustStore = new FileInputStream(connettore.getSslTsLocation());
                truststore.load(finTrustStore, connettore.getSslTsPasswd().toCharArray());
                TrustManagerFactory trustManagerFactory = TrustManagerFactory
                        .getInstance(TrustManagerFactory.getDefaultAlgorithm());
                trustManagerFactory.init(truststore);
                tm = trustManagerFactory.getTrustManagers();

                // Creo contesto SSL
                sslContext = SSLContext.getInstance(connettore.getSslType());
                sslContext.init(km, tm, null);
                sslContexts.put(bundleKey, sslContext);
            } catch (Exception e) {
                throw new ClientException(e);
            }
        }
    }

    if (connettore.getTipoAutenticazione().equals(EnumAuthType.HTTPBasic)) {
        ishttpBasicEnabled = true;
        httpBasicUser = connettore.getHttpUser();
        httpBasicPassword = connettore.getHttpPassw();
    }
}