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.apache.hadoop.crypto.key.RangerKMSDB.java

private void updateDBSSLURL() {
    if (conf != null && conf.get(PROPERTY_PREFIX + DB_SSL_ENABLED) != null) {
        String db_ssl_enabled = conf.get(PROPERTY_PREFIX + DB_SSL_ENABLED);
        if (StringUtils.isEmpty(db_ssl_enabled) || !"true".equalsIgnoreCase(db_ssl_enabled)) {
            db_ssl_enabled = "false";
        }//from w  w  w. jav  a 2s.c  om
        db_ssl_enabled = db_ssl_enabled.toLowerCase();
        if ("true".equalsIgnoreCase(db_ssl_enabled)) {
            String db_ssl_required = conf.get(PROPERTY_PREFIX + DB_SSL_REQUIRED);
            if (StringUtils.isEmpty(db_ssl_required) || !"true".equalsIgnoreCase(db_ssl_required)) {
                db_ssl_required = "false";
            }
            db_ssl_required = db_ssl_required.toLowerCase();
            String db_ssl_verifyServerCertificate = conf.get(PROPERTY_PREFIX + DB_SSL_VerifyServerCertificate);
            if (StringUtils.isEmpty(db_ssl_verifyServerCertificate)
                    || !"true".equalsIgnoreCase(db_ssl_verifyServerCertificate)) {
                db_ssl_verifyServerCertificate = "false";
            }
            db_ssl_verifyServerCertificate = db_ssl_verifyServerCertificate.toLowerCase();
            conf.set(PROPERTY_PREFIX + DB_SSL_ENABLED, db_ssl_enabled);
            conf.set(PROPERTY_PREFIX + DB_SSL_REQUIRED, db_ssl_required);
            conf.set(PROPERTY_PREFIX + DB_SSL_VerifyServerCertificate, db_ssl_verifyServerCertificate);
            String ranger_jpa_jdbc_url = conf.get(PROPERTY_PREFIX + DB_URL);
            if (!StringUtils.isEmpty(ranger_jpa_jdbc_url)) {
                StringBuffer ranger_jpa_jdbc_url_ssl = new StringBuffer(ranger_jpa_jdbc_url);
                ranger_jpa_jdbc_url_ssl.append("?useSSL=" + db_ssl_enabled + "&requireSSL=" + db_ssl_required
                        + "&verifyServerCertificate=" + db_ssl_verifyServerCertificate);
                conf.set(PROPERTY_PREFIX + DB_URL, ranger_jpa_jdbc_url_ssl.toString());
                DB_PROPERTIES.put(JPA_DB_URL, conf.get(PROPERTY_PREFIX + DB_URL));
                logger.info(PROPERTY_PREFIX + DB_URL + "=" + ranger_jpa_jdbc_url_ssl.toString());
            }

            if ("true".equalsIgnoreCase(db_ssl_verifyServerCertificate)) {
                if (conf != null) {
                    // update system key store path with custom key store.
                    String keystore = conf.get(PROPERTY_PREFIX + DB_SSL_KEYSTORE);
                    if (!StringUtils.isEmpty(keystore)) {
                        Path path = Paths.get(keystore);
                        if (Files.exists(path) && Files.isReadable(path)) {
                            System.setProperty("javax.net.ssl.keyStore",
                                    conf.get(PROPERTY_PREFIX + DB_SSL_KEYSTORE));
                            System.setProperty("javax.net.ssl.keyStorePassword",
                                    conf.get(PROPERTY_PREFIX + DB_SSL_KEYSTORE_PASSWORD));
                            System.setProperty("javax.net.ssl.keyStoreType", KeyStore.getDefaultType());
                        } else {
                            logger.debug("Could not find or read keystore file '" + keystore + "'");
                        }
                    } else {
                        logger.debug("keystore property '" + PROPERTY_PREFIX + DB_SSL_KEYSTORE
                                + "' value not found!");
                    }
                    // update system trust store path with custom trust store.
                    String truststore = conf.get(PROPERTY_PREFIX + DB_SSL_TRUSTSTORE);
                    if (!StringUtils.isEmpty(truststore)) {
                        Path path = Paths.get(truststore);
                        if (Files.exists(path) && Files.isReadable(path)) {
                            System.setProperty("javax.net.ssl.trustStore",
                                    conf.get(PROPERTY_PREFIX + DB_SSL_TRUSTSTORE));
                            System.setProperty("javax.net.ssl.trustStorePassword",
                                    conf.get(PROPERTY_PREFIX + DB_SSL_TRUSTSTORE_PASSWORD));
                            System.setProperty("javax.net.ssl.trustStoreType", KeyStore.getDefaultType());
                        } else {
                            logger.debug("Could not find or read truststore file '" + truststore + "'");
                        }
                    } else {
                        logger.debug("truststore property '" + PROPERTY_PREFIX + DB_SSL_TRUSTSTORE
                                + "' value not found!");
                    }
                }
            }
        }
    }
}

From source file:com.openshift.restclient.ClientBuilder.java

private TrustManagerFactory initTrustManagerFactory(String alias, X509Certificate cert,
        Collection<X509Certificate> certs)
        throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException {
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    if (alias != null && (cert != null || certs != null)) {
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        // need this load to initialize the key store, and allow for the subsequent set certificate entry
        ks.load(null, null);//from  w ww.  j  a  v  a  2  s . com
        if (cert != null) {
            cert.checkValidity();
            ks.setCertificateEntry(alias, cert);
        }
        if (certs != null) {
            int i = 0;
            for (X509Certificate x509 : certs) {
                x509.checkValidity();
                ks.setCertificateEntry(alias + i, x509);
                i++;
            }
        }

        // testing has proven that you can only call init() once for a TrustManagerFactory wrt loading certs
        // from the KeyStore ... subsequent KeyStore.setCertificateEntry / TrustManagerFactory.init calls are 
        // ignored.
        // So if a specific cert is required to validate this connection's communication with the server, add it up front
        // in the ctor.
        trustManagerFactory.init(ks);
    } else {
        trustManagerFactory.init((KeyStore) null);
    }
    return trustManagerFactory;
}

From source file:com.comcast.cdn.traffic_control.traffic_router.core.external.RouterTest.java

@Before
public void before() throws Exception {
    ObjectMapper objectMapper = new ObjectMapper(new JsonFactory());

    String resourcePath = "internal/api/1.3/steering.json";
    InputStream inputStream = getClass().getClassLoader().getResourceAsStream(resourcePath);

    if (inputStream == null) {
        fail("Could not find file '" + resourcePath
                + "' needed for test from the current classpath as a resource!");
    }/*  w ww . j  a v  a  2  s.  com*/

    Set<String> steeringDeliveryServices = new HashSet<String>();
    JsonNode steeringData = objectMapper.readTree(inputStream).get("response");
    Iterator<JsonNode> elements = steeringData.elements();

    while (elements.hasNext()) {
        JsonNode ds = elements.next();
        String dsId = ds.get("deliveryService").asText();
        steeringDeliveryServices.add(dsId);
    }

    resourcePath = "publish/CrConfig.json";
    inputStream = getClass().getClassLoader().getResourceAsStream(resourcePath);
    if (inputStream == null) {
        fail("Could not find file '" + resourcePath
                + "' needed for test from the current classpath as a resource!");
    }

    JsonNode jsonNode = objectMapper.readTree(inputStream);

    deliveryServiceId = null;

    Iterator<String> deliveryServices = jsonNode.get("deliveryServices").fieldNames();
    while (deliveryServices.hasNext()) {
        String dsId = deliveryServices.next();

        if (steeringDeliveryServices.contains(dsId)) {
            continue;
        }

        JsonNode deliveryServiceNode = jsonNode.get("deliveryServices").get(dsId);
        Iterator<JsonNode> matchsets = deliveryServiceNode.get("matchsets").iterator();

        while (matchsets.hasNext() && deliveryServiceId == null) {
            if ("HTTP".equals(matchsets.next().get("protocol").asText())) {
                final boolean sslEnabled = JsonUtils.optBoolean(deliveryServiceNode, "sslEnabled");
                if (!sslEnabled) {
                    deliveryServiceId = dsId;
                    deliveryServiceDomain = deliveryServiceNode.get("domains").get(0).asText();
                }
            }
        }
    }

    assertThat(deliveryServiceId, not(nullValue()));
    assertThat(deliveryServiceDomain, not(nullValue()));
    assertThat(httpsOnlyId, not(nullValue()));
    assertThat(httpsOnlyDomain, not(nullValue()));

    Iterator<String> cacheIds = jsonNode.get("contentServers").fieldNames();
    while (cacheIds.hasNext()) {
        String cacheId = cacheIds.next();
        JsonNode cacheNode = jsonNode.get("contentServers").get(cacheId);

        if (!cacheNode.has("deliveryServices")) {
            continue;
        }

        if (cacheNode.get("deliveryServices").has(deliveryServiceId)) {
            int port = cacheNode.get("port").asInt();
            String portText = (port == 80) ? "" : ":" + port;
            validLocations.add("http://" + cacheId + "." + deliveryServiceDomain + portText
                    + "/stuff?fakeClientIpAddress=12.34.56.78");
            validLocations.add("http://" + cacheId + "." + deliveryServiceDomain + portText
                    + "/stuff?fakeClientIpAddress=12.34.56.78&format=json");
        }

        if (cacheNode.get("deliveryServices").has(httpsOnlyId)) {
            int port = cacheNode.has("httpsPort") ? cacheNode.get("httpsPort").asInt(443) : 443;

            String portText = (port == 443) ? "" : ":" + port;
            httpsOnlyLocations.add("https://" + cacheId + "." + httpsOnlyDomain + portText
                    + "/stuff?fakeClientIpAddress=12.34.56.78");
        }

        if (cacheNode.get("deliveryServices").has(httpsNoCertsId)) {
            int port = cacheNode.has("httpsPort") ? cacheNode.get("httpsPort").asInt(443) : 443;

            String portText = (port == 443) ? "" : ":" + port;
            httpsNoCertsLocations.add("https://" + cacheId + "." + httpsNoCertsDomain + portText
                    + "/stuff?fakeClientIpAddress=12.34.56.78");
        }

        if (cacheNode.get("deliveryServices").has(httpAndHttpsId)) {
            int port = cacheNode.has("httpsPort") ? cacheNode.get("httpsPort").asInt(443) : 443;

            String portText = (port == 443) ? "" : ":" + port;
            httpAndHttpsLocations.add("https://" + cacheId + "." + httpAndHttpsDomain + portText
                    + "/stuff?fakeClientIpAddress=12.34.56.78");

            port = cacheNode.has("port") ? cacheNode.get("port").asInt(80) : 80;
            portText = (port == 80) ? "" : ":" + port;
            httpAndHttpsLocations.add("http://" + cacheId + "." + httpAndHttpsDomain + portText
                    + "/stuff?fakeClientIpAddress=12.34.56.78");
        }

        if (cacheNode.get("deliveryServices").has(httpToHttpsId)) {
            int port = cacheNode.has("httpsPort") ? cacheNode.get("httpsPort").asInt(443) : 443;

            String portText = (port == 443) ? "" : ":" + port;
            httpToHttpsLocations.add("https://" + cacheId + "." + httpToHttpsDomain + portText
                    + "/stuff?fakeClientIpAddress=12.34.56.78");
        }

        if (cacheNode.get("deliveryServices").has(httpOnlyId)) {
            int port = cacheNode.has("port") ? cacheNode.get("port").asInt(80) : 80;

            String portText = (port == 80) ? "" : ":" + port;
            httpOnlyLocations.add("http://" + cacheId + "." + httpOnlyDomain + portText
                    + "/stuff?fakeClientIpAddress=12.34.56.78");
        }
    }

    assertThat(validLocations.isEmpty(), equalTo(false));
    assertThat(httpsOnlyLocations.isEmpty(), equalTo(false));

    trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    InputStream keystoreStream = getClass().getClassLoader().getResourceAsStream("keystore.jks");
    trustStore.load(keystoreStream, "changeit".toCharArray());
    TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()).init(trustStore);

    httpClient = HttpClientBuilder.create()
            .setSSLSocketFactory(new ClientSslSocketFactory("tr.https-only-test.thecdn.example.com"))
            .setSSLHostnameVerifier(new TestHostnameVerifier()).disableRedirectHandling().build();

}

From source file:com.vangent.hieos.services.sts.util.STSUtil.java

/**
 *
 * @param stsConfig// w w w .  j a  v  a 2 s . c  om
 * @return
 * @throws STSException
 */
public static KeyStore getKeyStore(STSConfig stsConfig) throws STSException {
    KeyStore ks;
    try {
        ks = KeyStore.getInstance(KeyStore.getDefaultType());
        String keyStorePassword = stsConfig.getKeyStorePassword();
        char[] password = keyStorePassword.toCharArray();
        FileInputStream fis = new FileInputStream(stsConfig.getKeyStoreFileName());
        ks.load(fis, password);
        fis.close();
    } catch (Exception ex) {
        throw new STSException("Problem loading keystore: " + ex.getMessage());
    }
    return ks;
}

From source file:org.seedstack.seed.crypto.internal.EncryptionServiceFactoryTest.java

/**
 * Test method for//  w w w. ja  va2s .  c om
 * {@link org.seedstack.seed.crypto.internal.EncryptionServiceFactory#createEncryptionService(org.seedstack.seed.crypto.internal.KeyStoreDefinition, org.seedstack.seed.crypto.internal.CertificateDefinition)}
 * . Test a {@link CertificateException} if keystore can not be loaded.
 *
 * @throws Exception if an error occurred
 */
@Test(expected = RuntimeException.class)
public void testCreateEncryptionServiceWithKeystoreCertificateException(
        @Mocked final KeyStoreDefinition keyStoreDefinition,
        @Mocked final CertificateDefinition certificateDefinition, @Mocked final KeyStore keyStore,
        @Mocked final FileInputStream file,
        @SuppressWarnings("unused") @Mocked final EncryptionServiceImpl asymetricCrypting) throws Exception {
    new Expectations() {
        final String pathToKeystore = "pathToKeystore";
        final String password = "password";

        {
            keyStoreDefinition.getPath();
            returns(pathToKeystore);

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

            new FileInputStream(pathToKeystore);
            result = file;

            keyStoreDefinition.getPassword();
            returns(password);

            keyStore.load(file, password.toCharArray());
            result = new CertificateException("dummy exception");
        }
    };

    EncryptionServiceFactory factory = new EncryptionServiceFactory();
    factory.createEncryptionService(keyStoreDefinition, certificateDefinition);

}

From source file:com.evrythng.java.wrapper.core.api.ApiCommand.java

private static HttpClient wrapClient(final HttpClient base) {

    try {/*from  w w  w  .  j  a va  2 s.c o m*/
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        SSLSocketFactory ssf = new WrapperSSLSocketFactory(trustStore);
        ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = base.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", ssf, 443));
        return new DefaultHttpClient(ccm, base.getParams());
    } catch (Exception ex) {
        return null;
    }
}

From source file:org.ovirt.engine.sdk.web.ConnectionsPoolBuilder.java

/**
 * Creates SchemeRegistry// ww  w.j av a 2s . c  o m
 *
 * @param url
 * @param port
 *
 * @return {@link SchemeRegistry}
 */
private SchemeRegistry createSchemeRegistry(String url, int port) {
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    String protocol = getProtocol(url);
    SSLSocketFactory sf;

    if (HTTP_PROTOCOL.equals(protocol)) {
        schemeRegistry.register(new Scheme(HTTP_PROTOCOL, port, PlainSocketFactory.getSocketFactory()));
    } else if (HTTPS_PROTOCOL.equals(protocol)) {
        try {
            if (this.noHostVerification) {
                SSLContext sslcontext = SSLContext.getInstance("TLS");
                sslcontext.init(null, new TrustManager[] { noCaTrustManager }, null);
                sf = new SSLSocketFactory(sslcontext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            } else {
                KeyStore truststore = null;
                InputStream in = null;

                if (this.keyStorePath != null) {
                    truststore = KeyStore.getInstance(KeyStore.getDefaultType());
                    try {
                        in = new FileInputStream(this.keyStorePath);
                        truststore.load(in,
                                this.keyStorePassword != null ? this.keyStorePassword.toCharArray() : null);

                    } finally {
                        if (in != null) {
                            in.close();
                        }
                    }
                }
                sf = new SSLSocketFactory(SSLSocketFactory.TLS, null, null, truststore, null, null,
                        SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
            }

            schemeRegistry.register(new Scheme(HTTPS_PROTOCOL, port, sf));

        } catch (NoSuchAlgorithmException e) {
            throw new SocketFactoryException(NO_TLS_ERROR, e);
        } catch (KeyManagementException e) {
            throw new SocketFactoryException(BAD_KEY_ERROR, e);
        } catch (KeyStoreException e) {
            throw new SocketFactoryException(KEY_STORE_ERROR, e);
        } catch (FileNotFoundException e) {
            throw new SocketFactoryException(KEY_STORE_FILE_NOT_FOUND_ERROR, e);
        } catch (CertificateException e) {
            throw new SocketFactoryException(CERTEFICATE_ERROR, e);
        } catch (IOException e) {
            throw new SocketFactoryException(IO_ERROR, e);
        } catch (UnrecoverableKeyException e) {
            throw new SocketFactoryException(UNRECOVERABLE_KEY_ERROR, e);
        }
    } else {
        throw new ProtocolException(BAD_PROTOCOL_ERROR + protocol);
    }

    return schemeRegistry;
}

From source file:com.pyj.http.AsyncHttpClient.java

private SSLSocketFactory getSSLSocketFactory() {
    SSLSocketFactory sf = null;//from w ww. ja  v  a 2  s. c  om
    try {
        KeyStore store = KeyStore.getInstance(KeyStore.getDefaultType());
        store.load(null, null);
        sf = new SSLSocketFactoryEx(store);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); // ??
    } catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (CertificateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return sf;
}

From source file:com.vmware.identity.idm.server.clientcert.IdmClientCertificateValidator.java

/**
 *
 * @return keyStore representing that containing the trust CA certificates of the tenant
 * @throws InvalidArgumentException//ww  w. j  a  v  a2 s.com
 */
private KeyStore getTrustedClientCaStore() throws InvalidArgumentException {
    KeyStore trustedClientCaStore;

    if (certPolicy == null || certPolicy.getTrustedCAs() == null) {
        throw new InvalidArgumentException("Null client certificate policy or trust ca certficagtes.");
    }
    try {
        trustedClientCaStore = KeyStore.getInstance(KeyStore.getDefaultType());
    } catch (KeyStoreException e1) {
        throw new InvalidArgumentException("Failed in creating a keyStore instance: ", e1);
    }
    try {
        trustedClientCaStore.load(null, null);
    } catch (NoSuchAlgorithmException | CertificateException | IOException e1) {
        throw new InvalidArgumentException("Failed in initializing a keyStore instance: " + e1.getMessage(),
                e1);
    }
    for (Certificate trustCa : certPolicy.getTrustedCAs()) {
        X509Certificate x509Cert = (X509Certificate) trustCa;
        try {
            trustedClientCaStore.setCertificateEntry(x509Cert.getSubjectX500Principal().getName(), trustCa);
        } catch (KeyStoreException e) {
            throw new InvalidArgumentException("Failed in storing a ca cert to keyStore: " + e.getMessage(), e);
        }
    }
    return trustedClientCaStore;
}

From source file:com.google.wireless.speed.speedometer.Checkin.java

/**
 * Return an appropriately-configured HTTP client.
 *///w ww  .j  av a  2 s.co m
private HttpClient getNewHttpClient() {
    DefaultHttpClient client;
    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new MySSLSocketFactory(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);

        HttpConnectionParams.setConnectionTimeout(params, POST_TIMEOUT_MILLISEC);
        HttpConnectionParams.setSoTimeout(params, POST_TIMEOUT_MILLISEC);

        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);
        client = new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        Log.w(SpeedometerApp.TAG, "Unable to create SSL HTTP client", e);
        client = new DefaultHttpClient();
    }

    // TODO(mdw): For some reason this is not sending the cookie to the
    // test server, probably because the cookie itself is not properly
    // initialized. Below I manually set the Cookie header instead.
    CookieStore store = new BasicCookieStore();
    store.addCookie(authCookie);
    client.setCookieStore(store);
    return client;
}