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.codice.ddf.cxf.client.impl.SecureCxfClientFactoryImpl.java

@SuppressWarnings("squid:S3776")
private void configureConduit(ClientConfiguration clientConfig) {
    HTTPConduit httpConduit = clientConfig.getHttpConduit();
    if (httpConduit == null) {
        LOGGER.info("HTTPConduit was null for {}. Unable to configure security.", this);
        return;//from www . j  ava2s  .  co  m
    }

    if (allowRedirects) {
        HTTPClientPolicy clientPolicy = httpConduit.getClient();
        if (clientPolicy != null) {
            clientPolicy.setAutoRedirect(true);
            Bus bus = clientConfig.getBus();
            if (bus != null) {
                bus.getProperties().put(AUTO_REDIRECT_ALLOW_REL_URI, true);
                bus.getProperties().put(AUTO_REDIRECT_MAX_SAME_URI_COUNT, getSameUriRedirectMax());
            }
        }
    }

    TLSClientParameters tlsParams = httpConduit.getTlsClientParameters();
    if (tlsParams == null) {
        tlsParams = new TLSClientParameters();
    }

    tlsParams.setDisableCNCheck(disableCnCheck);

    tlsParams.setUseHttpsURLConnectionDefaultHostnameVerifier(!disableCnCheck);
    String cipherSuites = System.getProperty("https.cipherSuites");
    if (cipherSuites != null) {
        tlsParams.setCipherSuites(Arrays.asList(cipherSuites.split(",")));
    }

    KeyStore keyStore = null;
    KeyStore trustStore = null;
    try {
        keyStore = SecurityConstants.newKeystore();
        trustStore = SecurityConstants.newTruststore();
    } catch (KeyStoreException e) {
        LOGGER.debug("Unable to create keystore instance of type {}",
                System.getProperty(SecurityConstants.KEYSTORE_TYPE), e);
    }
    Path keyStoreFile;
    if (keyInfo != null && StringUtils.isNotBlank(keyInfo.getKeystorePath())) {
        keyStoreFile = Paths.get(keyInfo.getKeystorePath());
    } else {
        keyStoreFile = Paths.get(SecurityConstants.getKeystorePath());
    }

    Path trustStoreFile = Paths.get(SecurityConstants.getTruststorePath());
    String ddfHome = System.getProperty("ddf.home");
    if (ddfHome != null) {
        Path ddfHomePath = Paths.get(ddfHome);
        if (!keyStoreFile.isAbsolute()) {
            keyStoreFile = Paths.get(ddfHomePath.toString(), keyStoreFile.toString());
        }
        if (!trustStoreFile.isAbsolute()) {
            trustStoreFile = Paths.get(ddfHomePath.toString(), trustStoreFile.toString());
        }
    }
    String keyStorePassword = SecurityConstants.getKeystorePassword();
    String trustStorePassword = SecurityConstants.getTruststorePassword();
    if (!Files.isReadable(keyStoreFile) || !Files.isReadable(trustStoreFile)) {
        LOGGER.debug("Unable to read system key/trust store files: [ {} ] [ {} ]", keyStoreFile,
                trustStoreFile);
        return;
    }
    try (InputStream kfis = Files.newInputStream(keyStoreFile)) {
        if (keyStore != null) {
            keyStore.load(kfis, keyStorePassword.toCharArray());
        }
    } catch (NoSuchAlgorithmException | CertificateException | IOException e) {
        LOGGER.debug("Unable to load system key file.", e);
    }
    try (InputStream tfis = Files.newInputStream(trustStoreFile)) {
        if (trustStore != null) {
            trustStore.load(tfis, trustStorePassword.toCharArray());
        }
    } catch (NoSuchAlgorithmException | CertificateException | IOException e) {
        LOGGER.debug("Unable to load system trust file.", e);
    }

    KeyManager[] keyManagers = null;
    try {
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, keyStorePassword.toCharArray());
        keyManagers = keyManagerFactory.getKeyManagers();
        tlsParams.setKeyManagers(keyManagers);
    } catch (NoSuchAlgorithmException | KeyStoreException | UnrecoverableKeyException e) {
        LOGGER.debug("Unable to initialize KeyManagerFactory.", e);
    }

    TrustManager[] trustManagers = null;
    try {
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);
        trustManagers = trustManagerFactory.getTrustManagers();
        tlsParams.setTrustManagers(trustManagers);
    } catch (NoSuchAlgorithmException | KeyStoreException e) {
        LOGGER.debug("Unable to initialize TrustManagerFactory.", e);
    }

    if (keyInfo != null) {
        LOGGER.trace("Using keystore file: {}, alias: {}", keyStoreFile, keyInfo.getAlias());
        tlsParams.setUseHttpsURLConnectionDefaultSslSocketFactory(false);
        tlsParams.setCertAlias(keyInfo.getAlias());
        try {
            if (keyManagers == null) {
                throw new KeyManagementException("keyManagers was null");
            }

            boolean validProtocolFound = false;
            String validProtocolsStr = System.getProperty("jdk.tls.client.protocols");
            if (StringUtils.isNotBlank(validProtocolsStr)) {
                String[] validProtocols = validProtocolsStr.split(",");
                for (String validProtocol : validProtocols) {
                    if (validProtocol.equals(sslProtocol)) {
                        validProtocolFound = true;
                        break;
                    }
                }
                if (!validProtocolFound) {
                    LOGGER.error("{} is not in list of valid SSL protocols {}", sslProtocol, validProtocolsStr);
                }

            } else {
                validProtocolFound = true;
            }
            if (validProtocolFound) {
                tlsParams.setSSLSocketFactory(
                        getSSLSocketFactory(sslProtocol, keyInfo.getAlias(), keyManagers, trustManagers));
            }
        } catch (KeyManagementException | NoSuchAlgorithmException e) {
            LOGGER.debug("Unable to override default SSL Socket Factory", e);
        }
    } else {
        tlsParams.setUseHttpsURLConnectionDefaultSslSocketFactory(true);
        tlsParams.setCertAlias(SystemBaseUrl.INTERNAL.getHost());
    }

    httpConduit.setTlsClientParameters(tlsParams);
}

From source file:org.apache.cassandra.hadoop.cql3.CqlConfigHelper.java

private static SSLContext getSSLContext(String truststorePath, String truststorePassword, String keystorePath,
        String keystorePassword) throws NoSuchAlgorithmException, KeyStoreException, CertificateException,
        IOException, UnrecoverableKeyException, KeyManagementException {
    SSLContext ctx;/*ww w. j a v  a 2  s  . c o  m*/
    try (FileInputStream tsf = new FileInputStream(truststorePath);
            FileInputStream ksf = new FileInputStream(keystorePath)) {
        ctx = SSLContext.getInstance("SSL");

        KeyStore ts = KeyStore.getInstance("JKS");
        ts.load(tsf, truststorePassword.toCharArray());
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ts);

        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(ksf, keystorePassword.toCharArray());
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(ks, keystorePassword.toCharArray());

        ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());
    }
    return ctx;
}

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

public SSLSocketFactory getTunnelSSLSocketFactory(String hostname) {

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

    //   KeyStore ks;
    try {//from  ww  w . j  a va2  s .  c o m
        SSLContext ctx = SSLContext.getInstance(SSL);
        // Normally "SunX509", "IbmX509"...
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());

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

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

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

        return tunnelSSLFactory;

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

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

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

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

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

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

From source file:org.apache.nifi.controller.livy.LivySessionController.java

private void setSslSocketFactory(HttpsURLConnection httpsURLConnection, SSLContextService sslService,
        SSLContext sslContext) throws IOException, KeyStoreException, CertificateException,
        NoSuchAlgorithmException, UnrecoverableKeyException, KeyManagementException {
    final String keystoreLocation = sslService.getKeyStoreFile();
    final String keystorePass = sslService.getKeyStorePassword();
    final String keystoreType = sslService.getKeyStoreType();

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

    try (FileInputStream keyStoreStream = new FileInputStream(keystoreLocation)) {
        keyStore.load(keyStoreStream, keystorePass.toCharArray());
    }//from w  ww  .  j a  v  a  2 s  .  co m

    final KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, keystorePass.toCharArray());

    // load truststore
    final String truststoreLocation = sslService.getTrustStoreFile();
    final String truststorePass = sslService.getTrustStorePassword();
    final String truststoreType = sslService.getTrustStoreType();

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

    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

    final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
    httpsURLConnection.setSSLSocketFactory(sslSocketFactory);
}

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  w w  w.  j  a  v  a2s . co 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.araqne.pkg.PackageManagerService.java

private byte[] download(PackageRepository repo, URL url)
        throws IOException, KeyStoreException, UnrecoverableKeyException, KeyManagementException {
    if (repo.isLocalFilesystem()) {
        FileInputStream stream = null;
        try {//from w w  w  .j  a va 2s.co m
            File file = new File(url.toURI());
            long length = file.length();
            stream = new FileInputStream(file);
            byte[] b = new byte[(int) length];
            stream.read(b);
            return b;
        } catch (URISyntaxException e) {
            e.printStackTrace();
            return new byte[0];
        } finally {
            if (stream != null)
                stream.close();
        }
    } else if (repo.isHttps()) {
        ServiceReference<?> ref = bc.getServiceReference(KeyStoreManager.class.getName());
        KeyStoreManager keyman = (KeyStoreManager) bc.getService(ref);
        try {
            TrustManagerFactory tmf = keyman.getTrustManagerFactory(repo.getTrustStoreAlias(),
                    TrustManagerFactory.getDefaultAlgorithm());
            KeyManagerFactory kmf = keyman.getKeyManagerFactory(repo.getKeyStoreAlias(),
                    KeyManagerFactory.getDefaultAlgorithm());
            HttpWagon.download(url, tmf, kmf);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return HttpWagon.download(url);
    } else if (repo.isAuthRequired())
        return HttpWagon.download(url, true, repo.getAccount(), repo.getPassword());
    return HttpWagon.download(url);
}

From source file:org.araqne.pkg.PackageManagerService.java

private String downloadString(PackageRepository repo, URL url)
        throws IOException, KeyStoreException, UnrecoverableKeyException, KeyManagementException {
    if (repo.isLocalFilesystem()) {
        FileInputStream stream = null;
        try {// w  w w  .  j av a  2 s.co  m
            File file = new File(url.toURI());
            long length = file.length();
            stream = new FileInputStream(file);
            byte[] b = new byte[(int) length];
            stream.read(b);
            return new String(b, Charset.forName("UTF-8"));
        } catch (URISyntaxException e) {
            e.printStackTrace();
            return new String();
        } finally {
            if (stream != null)
                stream.close();
        }
    } else if (repo.isHttps()) {
        ServiceReference<?> ref = bc.getServiceReference(KeyStoreManager.class.getName());
        KeyStoreManager keyman = (KeyStoreManager) bc.getService(ref);
        try {
            TrustManagerFactory tmf = keyman.getTrustManagerFactory(repo.getTrustStoreAlias(),
                    TrustManagerFactory.getDefaultAlgorithm());
            KeyManagerFactory kmf = keyman.getKeyManagerFactory(repo.getKeyStoreAlias(),
                    KeyManagerFactory.getDefaultAlgorithm());
            HttpWagon.download(url, tmf, kmf);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return HttpWagon.downloadString(url);
    } else if (repo.isAuthRequired())
        return HttpWagon.downloadString(url, repo.getAccount(), repo.getPassword());
    return HttpWagon.downloadString(url);
}