Example usage for java.security KeyStore getDefaultType

List of usage examples for java.security KeyStore getDefaultType

Introduction

In this page you can find the example usage for java.security KeyStore getDefaultType.

Prototype

public static final String getDefaultType() 

Source Link

Document

Returns the default keystore type as specified by the keystore.type security property, or the string "jks" (acronym for "Java keystore" ) if no such property exists.

Usage

From source file:org.muhia.app.psi.integ.config.ke.shared.SharedWsClientConfiguration.java

@Bean(name = "sharedSecureHttpClient")
public CloseableHttpClient secureHttpClient() {
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    try {/*from   ww  w. j  a  v a  2s. c om*/
        /*
        TODO: Modify to accept only specific certificates, test implementation is as below,
        TODO: need to find a way of determining if server url is https or not
        TODO: Whether we have imported the certificate or not
        */
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        Resource resource = loaderService.getResource(properties.getSharedKeystorePath());
        keyStore.load(resource.getInputStream(),
                hasher.getDecryptedValue(properties.getSharedKeystorePassword()).toCharArray());
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy())
                .loadKeyMaterial(keyStore,
                        hasher.getDecryptedValue(properties.getSharedKeystorePassword()).toCharArray())
                .build();
        //            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (certificate, authType) -> true).build();

        RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(properties.getSharedTransportConnectionTimeout())
                .setConnectionRequestTimeout(properties.getSharedTransportConnectionRequestTimeout())
                .setSocketTimeout(properties.getSharedTransportReadTimeout()).build();
        CredentialsProvider provider = new BasicCredentialsProvider();
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(
                sharedDataDTO.getTransportUsername(), sharedDataDTO.getTransportPassword());
        provider.setCredentials(AuthScope.ANY, credentials);

        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
        connManager.setMaxTotal(properties.getSharedPoolMaxHost());
        connManager.setDefaultMaxPerRoute(properties.getSharedPoolDefaultmaxPerhost());
        connManager.setValidateAfterInactivity(properties.getSharedPoolValidateAfterInactivity());
        httpClient = HttpClientBuilder.create().setSSLContext(sslContext)
                .setSSLHostnameVerifier(new NoopHostnameVerifier()).setDefaultRequestConfig(config)
                .setDefaultCredentialsProvider(provider).setConnectionManager(connManager)
                .evictExpiredConnections().addInterceptorFirst(new RemoveHttpHeadersInterceptor()).build();
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException | CertificateException
            | IOException | UnrecoverableKeyException e) {
        Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, e.getMessage(), e);
    }
    return httpClient;

}

From source file:org.apache.camel.component.file.remote.FtpsEndpoint.java

/**
 * Create the FTPS client./*from   w  w  w.j  ava2s . co m*/
 */
protected FTPClient createFtpClient() throws Exception {
    FTPSClient client = null;

    if (sslContextParameters != null) {
        SSLContext context = sslContextParameters.createSSLContext();

        client = new FTPSClient(getFtpsConfiguration().isImplicit(), context);

        // The FTPSClient tries to manage the following SSLSocket related configuration options
        // on its own based on internal configuration options.  FTPSClient does not lend itself
        // to subclassing for the purpose of overriding this behavior (private methods, fields, etc.).
        // As such, we create a socket (preconfigured by SSLContextParameters) from the context
        // we gave to FTPSClient and then setup FTPSClient to reuse the already configured configuration
        // from the socket for all future sockets it creates.  Not sexy and a little brittle, but it works.
        SSLSocket socket = (SSLSocket) context.getSocketFactory().createSocket();
        client.setEnabledCipherSuites(socket.getEnabledCipherSuites());
        client.setEnabledProtocols(socket.getEnabledProtocols());
        client.setNeedClientAuth(socket.getNeedClientAuth());
        client.setWantClientAuth(socket.getWantClientAuth());
        client.setEnabledSessionCreation(socket.getEnableSessionCreation());
    } else {
        client = new FTPSClient(getFtpsConfiguration().getSecurityProtocol(),
                getFtpsConfiguration().isImplicit());

        if (ftpClientKeyStoreParameters != null) {
            String type = (ftpClientKeyStoreParameters.containsKey("type"))
                    ? (String) ftpClientKeyStoreParameters.get("type")
                    : KeyStore.getDefaultType();
            String file = (String) ftpClientKeyStoreParameters.get("file");
            String password = (String) ftpClientKeyStoreParameters.get("password");
            String algorithm = (ftpClientKeyStoreParameters.containsKey("algorithm"))
                    ? (String) ftpClientKeyStoreParameters.get("algorithm")
                    : KeyManagerFactory.getDefaultAlgorithm();
            String keyPassword = (String) ftpClientKeyStoreParameters.get("keyPassword");

            KeyStore keyStore = KeyStore.getInstance(type);
            FileInputStream keyStoreFileInputStream = new FileInputStream(new File(file));
            try {
                keyStore.load(keyStoreFileInputStream, password.toCharArray());
            } finally {
                IOHelper.close(keyStoreFileInputStream, "keyStore", log);
            }

            KeyManagerFactory keyMgrFactory = KeyManagerFactory.getInstance(algorithm);
            keyMgrFactory.init(keyStore, keyPassword.toCharArray());
            client.setNeedClientAuth(true);
            client.setKeyManager(keyMgrFactory.getKeyManagers()[0]);
        }

        if (ftpClientTrustStoreParameters != null) {
            String type = (ftpClientTrustStoreParameters.containsKey("type"))
                    ? (String) ftpClientTrustStoreParameters.get("type")
                    : KeyStore.getDefaultType();
            String file = (String) ftpClientTrustStoreParameters.get("file");
            String password = (String) ftpClientTrustStoreParameters.get("password");
            String algorithm = (ftpClientTrustStoreParameters.containsKey("algorithm"))
                    ? (String) ftpClientTrustStoreParameters.get("algorithm")
                    : TrustManagerFactory.getDefaultAlgorithm();

            KeyStore trustStore = KeyStore.getInstance(type);
            FileInputStream trustStoreFileInputStream = new FileInputStream(new File(file));
            try {
                trustStore.load(trustStoreFileInputStream, password.toCharArray());
            } finally {
                IOHelper.close(trustStoreFileInputStream, "trustStore", log);
            }

            TrustManagerFactory trustMgrFactory = TrustManagerFactory.getInstance(algorithm);
            trustMgrFactory.init(trustStore);

            client.setTrustManager(trustMgrFactory.getTrustManagers()[0]);
        }
    }

    return client;
}

From source file:org.apache.qpid.systest.rest.RestTestHelper.java

public HttpURLConnection openManagementConnection(String path, String method) throws IOException {
    URL url = getManagementURL(path);
    HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
    if (_useSsl) {
        try {/*from w  w w .ja va 2 s  .com*/
            // We have to use a SSLSocketFactory from a new SSLContext so that we don't re-use
            // the JVM's defaults that may have been initialised in previous tests.

            SSLContext sslContext = SSLContextFactory.buildClientContext(TRUSTSTORE, TRUSTSTORE_PASSWORD,
                    KeyStore.getDefaultType(), TrustManagerFactory.getDefaultAlgorithm(), null, null, null,
                    null, null);

            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

            ((HttpsURLConnection) httpCon).setSSLSocketFactory(sslSocketFactory);
        } catch (GeneralSecurityException e) {
            throw new RuntimeException(e);
        }
    }

    if (_username != null) {
        String encoded = new String(new Base64().encode((_username + ":" + _password).getBytes()));
        httpCon.setRequestProperty("Authorization", "Basic " + encoded);
    }

    httpCon.setDoOutput(true);
    httpCon.setRequestMethod(method);
    return httpCon;
}

From source file:org.apache.ws.security.components.crypto.AbstractCrypto.java

/**
 * This allows providing a custom class loader to load the resources, etc
 * @param properties//ww w .  j a v  a  2s .  co  m
 * @param loader
 * @throws CredentialException
 * @throws IOException
 */
public AbstractCrypto(Properties properties, ClassLoader loader) throws CredentialException, IOException {
    this.properties = properties;
    if (this.properties == null) {
        return;
    }
    String location = this.properties.getProperty("org.apache.ws.security.crypto.merlin.file");
    if (location != null) {
        location = location.trim();
    }
    InputStream is = null;
    if (location != null) {
        java.net.URL url = Loader.getResource(loader, location);
        if (url != null) {
            is = url.openStream();
        } else {
            is = new java.io.FileInputStream(location);
        }

        /**
         * If we don't find it, then look on the file system.
         */
        if (is == null) {
            try {
                is = new FileInputStream(location);
            } catch (Exception e) {
                if (doDebug) {
                    log.debug(e.getMessage(), e);
                }
                throw new CredentialException(CredentialException.IO_ERROR, "proxyNotFound",
                        new Object[] { location }, e);
            }
        }
    }

    /**
     * Load the keystore
     */
    try {
        String provider = properties.getProperty("org.apache.ws.security.crypto.merlin.keystore.provider");
        if (provider != null) {
            provider = provider.trim();
        }
        String passwd = properties.getProperty("org.apache.ws.security.crypto.merlin.keystore.password",
                "security");
        if (passwd != null) {
            passwd = passwd.trim();
        }
        String type = properties.getProperty("org.apache.ws.security.crypto.merlin.keystore.type",
                KeyStore.getDefaultType());
        if (type != null) {
            type = type.trim();
        }
        this.keystore = load(is, passwd, provider, type);
    } finally {
        if (is != null) {
            is.close();
        }
    }

    /**
     * Load cacerts
     */
    String loadCacerts = properties.getProperty("org.apache.ws.security.crypto.merlin.load.cacerts", "true");
    if (loadCacerts != null) {
        loadCacerts = loadCacerts.trim();
    }
    if (Boolean.valueOf(loadCacerts).booleanValue()) {
        String cacertsPath = System.getProperty("java.home") + "/lib/security/cacerts";
        InputStream cacertsIs = new FileInputStream(cacertsPath);
        try {
            String cacertsPasswd = properties
                    .getProperty("org.apache.ws.security.crypto.merlin.cacerts.password", "changeit");
            if (cacertsPasswd != null) {
                cacertsPasswd = cacertsPasswd.trim();
            }
            this.cacerts = load(cacertsIs, cacertsPasswd, null, KeyStore.getDefaultType());
            if (doDebug) {
                log.debug("CA certs have been loaded");
            }
        } finally {
            cacertsIs.close();
        }
    } else {
        if (doDebug) {
            log.debug("CA certs have not been loaded");
        }
    }
}

From source file:org.openiot.gsn.http.rest.RestRemoteWrapper.java

public boolean initialize() {
    try {/*from www. j av a 2  s .  com*/
        initParams = new RemoteWrapperParamParser(getActiveAddressBean(), false);
        httpclient = new DefaultHttpClient(getHttpClientParams(initParams.getTimeout()));
        // Init the http client
        if (initParams.isSSLRequired()) {
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(new FileInputStream(new File("conf/servertestkeystore")),
                    Main.getContainerConfig().getSSLKeyStorePassword().toCharArray());
            SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);
            socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            int sslPort = Main.getContainerConfig().getSSLPort() > 0 ? Main.getContainerConfig().getSSLPort()
                    : ContainerConfig.DEFAULT_SSL_PORT;
            Scheme sch = new Scheme("https", socketFactory, sslPort);
            httpclient.getConnectionManager().getSchemeRegistry().register(sch);
        }
        Scheme plainsch = new Scheme("http", PlainSocketFactory.getSocketFactory(),
                Main.getContainerConfig().getContainerPort());
        httpclient.getConnectionManager().getSchemeRegistry().register(plainsch);
        //
        lastReceivedTimestamp = initParams.getStartTime();
        structure = connectToRemote();
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        return false;
    }
    return true;
}

From source file:ddf.security.settings.impl.SecuritySettingsServiceImpl.java

private KeyStore createKeyStore(String path, String password) {
    KeyStore keyStore = null;//  w ww .j av a2 s. com
    File keyStoreFile = new File(path);
    if (keyStoreFile.exists() && StringUtils.isNotBlank(password)) {
        FileInputStream fis = null;
        try {
            keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            fis = new FileInputStream(keyStoreFile);
            LOGGER.debug("Loading trustStore");
            keyStore.load(fis, password.toCharArray());
        } catch (KeyStoreException | CertificateException e) {
            LOGGER.warn("Issue while trying to load ");
        } catch (IOException e) {
            LOGGER.warn("Unable to load keystore file from path" + path, e);
        } catch (NoSuchAlgorithmException nsae) {
            LOGGER.warn("JVM implementation does not come with default keystore type", nsae);
        } finally {
            IOUtils.closeQuietly(fis);
        }
    }
    return keyStore;
}

From source file:com.blackboard.LearnServer.java

private AbstractHttpClient getTrustAllSSLHttpClient() {
    try {/*from w w  w. j  a  v  a 2s  . co  m*/
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new TrustAllSSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
        return new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        System.out.println("WARNING: Could not create Trust All SSL client, using default" + e.getMessage());
        return new DefaultHttpClient();
    }
}

From source file:org.apache.hive.service.server.TestHS2HttpServerPamConfiguration.java

private static void createDefaultKeyStore()
        throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException {
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    char[] password = keyStorePassword.toCharArray();
    ks.load(null, null);/*from   w w w.j a va  2s .  c  om*/

    // Store away the keystore.
    try (FileOutputStream fos = new FileOutputStream(sslKeyStorePath)) {
        ks.store(fos, password);
    }
}

From source file:com.linkedin.pinot.common.utils.ClientSSLContextGenerator.java

private TrustManager[] setupTrustManagers()
        throws CertificateException, KeyStoreException, IOException, NoSuchAlgorithmException {
    // This is the cert authority that validates server's cert, so we need to put it in our
    // trustStore.
    if (_serverCACertFile != null) {
        LOGGER.info("Initializing trust store from {}", _serverCACertFile);
        FileInputStream is = new FileInputStream(new File(_serverCACertFile));
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null);/*w ww .j a  v  a  2s  . c o m*/
        CertificateFactory certificateFactory = CertificateFactory.getInstance(CERTIFICATE_TYPE);
        int i = 0;
        while (is.available() > 0) {
            X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(is);
            LOGGER.info("Read certificate serial number {} by issuer {} ", cert.getSerialNumber().toString(16),
                    cert.getIssuerDN().toString());

            String serverKey = "https-server-" + i;
            trustStore.setCertificateEntry(serverKey, cert);
            i++;
        }

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(CERTIFICATE_TYPE);
        tmf.init(trustStore);
        LOGGER.info("Successfully initialized trust store");
        return tmf.getTrustManagers();
    }
    // Server verification disabled. Trust all servers
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] x509Certificates, String s)
                throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] x509Certificates, String s)
                throws CertificateException {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    } };
    return trustAllCerts;
}