Example usage for java.security KeyStore getInstance

List of usage examples for java.security KeyStore getInstance

Introduction

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

Prototype

public static KeyStore getInstance(String type) throws KeyStoreException 

Source Link

Document

Returns a keystore object of the specified type.

Usage

From source file:com.bt.pi.api.http.SimpleHttpsServerFactoryBean.java

protected HttpServer getInitializedServer(InetSocketAddress address) throws IOException {
    HttpsServer server = HttpsServer.create(address, getBacklog());
    try {/*from   w  w  w.  j  a  v  a  2 s .  c  o  m*/
        SSLContext sslContext = SSLContext.getInstance(sslContextProtocol);

        KeyStore ks = KeyStore.getInstance(keyStoreType);
        InputStream is = keyStoreLocation.getInputStream();
        try {
            ks.load(is, password);
        } catch (EOFException e) {
            LOG.warn(String.format(
                    "Unable to load certificate store %s. This may be possible because https isn't enabled with a valid certificate",
                    keyStoreLocation));
            return null;
        }

        KeyManagerFactory kmf = KeyManagerFactory.getInstance(keyManagerAlgorithm);
        kmf.init(ks, password);

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(trustManagerAlgorithm);
        tmf.init(ks);

        sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

        final SSLEngine m_engine = sslContext.createSSLEngine();

        server.setHttpsConfigurator(new HttpsConfigurator(sslContext) {
            public void configure(HttpsParameters params) {
                params.setSSLParameters(getSSLContext().getDefaultSSLParameters());
                params.setNeedClientAuth(false);
                params.setWantClientAuth(false);
                params.setCipherSuites(m_engine.getEnabledCipherSuites());
                params.setProtocols(m_engine.getEnabledProtocols());
            }
        });
    } catch (Throwable e) {
        throw new IOException("initializing HttpsServer failed due to exception", e);
    }
    return server;
}

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);//from  ww w . j a v a  2 s  .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;
}

From source file:com.longle1.facedetection.TimedAsyncHttpResponseHandler.java

public void executePut(String putURL, RequestParams params, byte[] bb) {
    try {// w  w w. j a  va  2s  .co  m
        AsyncHttpClient client = new AsyncHttpClient();
        ByteArrayEntity bae = null;
        bae = new ByteArrayEntity(bb);
        bae.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/octet-stream"));

        // Add SSL
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(mContext.getResources().openRawResource(R.raw.truststore), "changeit".toCharArray());
        SSLSocketFactory sf = new SSLSocketFactory(trustStore);
        client.setSSLSocketFactory(sf);

        client.setTimeout(30000);

        client.put(null, putURL + "?" + params.toString(), bae, null, this);
    } catch (Exception e) {
        e.printStackTrace();
    }
    Log.i("executePut", "done");
}

From source file:org.ops4j.pax.web.itest.base.client.HttpComponentsWrapper.java

private CloseableHttpClient createHttpClient() throws KeyStoreException, IOException, NoSuchAlgorithmException,
        CertificateException, KeyManagementException {
    HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    SSLConnectionSocketFactory sslsf = null;
    try {/* w w w .j  a  va  2  s  .c  o  m*/
        FileInputStream instream = new FileInputStream(new File(keyStore));
        try {
            trustStore.load(instream, "password".toCharArray());
        } finally {
            // CHECKSTYLE:OFF
            try {
                instream.close();
            } catch (Exception ignore) {
            }
            // CHECKSTYLE:ON
        }

        SSLContext sslContext = SSLContexts.custom().useTLS().loadTrustMaterial(trustStore).build();
        sslsf = new SSLConnectionSocketFactory(sslContext, (X509HostnameVerifier) hostnameVerifier);
    } catch (FileNotFoundException e) {
        LOG.error("Error preparing SSL for testing. Https will not be available.", e);
    }

    PlainConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();

    RegistryBuilder<ConnectionSocketFactory> rb = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", plainsf);
    if (sslsf != null) {
        rb.register("https", sslsf);
    }

    Registry<ConnectionSocketFactory> registry = rb.build();

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);

    return HttpClients.custom().setConnectionManager(cm).build();

}

From source file:mitm.common.tools.PfxTool.java

private static KeyStore loadKeyStore(String keyFile, boolean shouldExist, String password) throws Exception {
    File file = new File(keyFile);

    file = file.getAbsoluteFile();//from  w  w  w  .  j av  a 2s .  c o  m

    KeyStore keyStore = KeyStore.getInstance("PKCS12");

    if (shouldExist && !file.exists()) {
        throw new FileNotFoundException(keyFile + " pfx file not found.");
    }

    /* initialize key store */
    char[] pw = password != null ? password.toCharArray() : null;

    if (file.exists()) {
        InputStream input = new FileInputStream(file);
        keyStore.load(input, pw);
        input.close();
    } else {
        // creates an empty keystore
        keyStore.load(null, pw);
    }

    return keyStore;
}

From source file:com.brobwind.brodm.NetworkUtils.java

public static synchronized HttpClient getHttpClient(int port, int securePort, Callback callback) {
    try {/*from www .jav a2s . c om*/
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory factory = new MySSLSocketFactory(trustStore, callback);
        factory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

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

        ConnManagerParams.setTimeout(params, 10000);
        HttpConnectionParams.setConnectionTimeout(params, 10000);
        HttpConnectionParams.setSoTimeout(params, 100000);

        SchemeRegistry reg = new SchemeRegistry();
        reg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), port));
        reg.register(new Scheme("https", factory, securePort));

        ClientConnectionManager connManager = new ThreadSafeClientConnManager(params, reg);

        return new DefaultHttpClient(connManager, params);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return new DefaultHttpClient();
}

From source file:org.commonjava.indy.httprox.ProxyHttpsTest.java

protected KeyStore getTrustStore(File jks) throws Exception {
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    try (FileInputStream instream = new FileInputStream(jks)) {
        trustStore.load(instream, "passwd".toCharArray());
    }//from  w ww  . jav a 2  s. com
    return trustStore;
}

From source file:com.t2auth.AuthUtils.java

public static SSLContext getSslContext(Context ctx) {
    InputStream in = null;/* w w w .j av  a2s .c  o  m*/

    if (sSslContext == null) {
        try {
            sSslContext = SSLContext.getInstance("TLS");
            try {
                if (sKey == null) {
                    sKey = KeyStore.getInstance("BKS");
                    in = ctx.getResources().openRawResource(R.raw.keystore);
                    sKey.load(in, "itsatrap".toCharArray());
                }

                TrustManagerFactory tmf = TrustManagerFactory
                        .getInstance(TrustManagerFactory.getDefaultAlgorithm());
                tmf.init(sKey);
                KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509");
                kmf.init(sKey, "itsatrap".toCharArray());

                sSslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
                return sSslContext;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    } else {
        return sSslContext;
    }

    return null;
}