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.alliander.osgp.shared.usermanagement.OrganisationManagementClient.java

/**
 * Construct a UserManagementClient instance.
 *
 * @param keystoreLocation//from  ww w  .  j a  v a 2 s. c  om
 *            The location of the key store.
 * @param keystorePassword
 *            The password for the key store.
 * @param keystoreType
 *            The type of the key store.
 * @param baseAddress
 *            The base address or URL for the UserManagementClient.
 *
 * @throws OrganisationManagementClientException
 *             In case the construction fails, a
 *             OrganisationManagementClientException will be thrown.
 */
public OrganisationManagementClient(final String keystoreLocation, final String keystorePassword,
        final String keystoreType, final String baseAddress) throws OrganisationManagementClientException {

    InputStream stream = null;
    boolean isClosed = false;
    Exception exception = null;

    try {
        // Create the KeyStore.
        final KeyStore keystore = KeyStore.getInstance(keystoreType.toUpperCase());

        stream = new FileInputStream(keystoreLocation);
        keystore.load(stream, keystorePassword.toCharArray());

        // Create TrustManagerFactory and initialize it using the KeyStore.
        final TrustManagerFactory tmf = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(keystore);

        // Create Apache CXF WebClient with JSON provider.
        final List<Object> providers = new ArrayList<Object>();
        providers.add(new JacksonJaxbJsonProvider());

        this.webClient = WebClient.create(baseAddress, providers);
        if (this.webClient == null) {
            throw new UserManagementClientException("webclient is null");
        }

        // Set up the HTTP Conduit to use the TrustManagers.
        final ClientConfiguration config = WebClient.getConfig(this.webClient);
        final HTTPConduit conduit = config.getHttpConduit();

        conduit.setTlsClientParameters(new TLSClientParameters());
        conduit.getTlsClientParameters().setTrustManagers(tmf.getTrustManagers());
    } catch (final Exception e) {
        LOGGER.error(CONSTRUCTION_FAILED, e);
        throw new OrganisationManagementClientException(CONSTRUCTION_FAILED, e);
    } finally {
        try {
            stream.close();
            isClosed = true;
        } catch (final Exception streamCloseException) {
            LOGGER.error(CONSTRUCTION_FAILED, streamCloseException);
            exception = streamCloseException;
        }
    }

    if (!isClosed) {
        throw new OrganisationManagementClientException(CONSTRUCTION_FAILED, exception);
    }
}

From source file:com.emc.cto.ridagent.rid.test.TestScript.java

public static String httpSend(String output, String destURL) throws ParserConfigurationException, SAXException {

    /* Set up TLS mutual authentication */

    KeyStore keystore = null;//from w ww. j  av a 2  s  . c o  m
    String docid = null;
    try {
        keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    } catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    InputStream keystoreInput = null;
    try {
        keystoreInput = new FileInputStream(m_keystorePath);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    try {
        keystore.load(keystoreInput, m_keystorePassword.toCharArray());
    } 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();
    }
    try {
        if (logger.isDebugEnabled()) {
            logger.debug("Keystore has " + keystore.size() + " keys");
        }
    } catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    KeyStore truststore = null;
    try {
        truststore = KeyStore.getInstance(KeyStore.getDefaultType());
    } catch (KeyStoreException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    InputStream truststoreInput = null;
    try {
        truststoreInput = new FileInputStream(m_truststorePath);
    } catch (FileNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    try {
        truststore.load(truststoreInput, m_truststorePassword.toCharArray());
    } catch (NoSuchAlgorithmException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (CertificateException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    SSLSocketFactory schemeSocketFactory = null;

    try {
        schemeSocketFactory = new SSLSocketFactory(keystore, m_keystorePassword, truststore);
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    schemeRegistry.register(new Scheme(m_protocol, m_port, schemeSocketFactory));
    final HttpParams httpParams = new BasicHttpParams();
    DefaultHttpClient httpClient = new DefaultHttpClient(new BasicClientConnectionManager(schemeRegistry),
            httpParams);

    /* Prepare the request to send */

    Map<String, Object> responseMap = new HashMap<String, Object>();

    HttpEntity request = new StringEntity(output, ContentType.TEXT_XML);

    //Create POST method
    HttpPost postMethod = new HttpPost(destURL);
    postMethod.setHeader("User-Agent", "EMC RID System");
    postMethod.setHeader("Content-Type", "text/xml");
    postMethod.setEntity(request);

    /* POST the request and process the response */
    HttpResponse httpResponse = null;
    int code;

    try {
        httpResponse = httpClient.execute(postMethod);
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    if (httpResponse.getEntity() != null) {

        code = httpResponse.getStatusLine().getStatusCode();

        try {
            InputStream xml = httpResponse.getEntity().getContent();

            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(xml);
            docid = doc.getElementsByTagName("iodef:IncidentID").item(0).getTextContent();
            System.out.println("ID of the newly created document   " + docid);
        } catch (ParseException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        responseMap.put("success", true);
        responseMap.put("statusCode", code);

    } else {
        responseMap.put("success", false);
        responseMap.put("errorMessage", "Send failed (fill in exception)");
    }

    return docid;
}

From source file:com.collabnet.tracker.common.httpClient.SslProtocolSocketFactory.java

private SslProtocolSocketFactory() {
    KeyManager[] keymanagers = null;
    if (System.getProperty(KEY_STORE) != null && System.getProperty(KEY_STORE_PASSWORD) != null) {
        try {/*ww w.j  ava  2s.  c  om*/
            String type = System.getProperty(KEY_STORE_TYPE, KeyStore.getDefaultType());
            KeyStore keyStore = KeyStore.getInstance(type);
            char[] password = System.getProperty(KEY_STORE_PASSWORD).toCharArray();
            FileInputStream keyStoreInputStream = new FileInputStream(System.getProperty(KEY_STORE));
            keyStore.load(keyStoreInputStream, password);
            keyStoreInputStream.close();
            KeyManagerFactory keyManagerFactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyManagerFactory.init(keyStore, password);
            keymanagers = keyManagerFactory.getKeyManagers();
        } catch (Exception e) {
            log(0, "Could not initialize keystore", e);
        }
    }

    hasKeyManager = keymanagers != null;

    try {
        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(keymanagers, new TrustManager[] { new TrustAllTrustManager() }, null);
        this.socketFactory = sslContext.getSocketFactory();
    } catch (Exception e) {
        log(0, "Could not initialize SSL context", e);
    }
}

From source file:com.mycompany.bankinterface.crypto.Signer.java

private void initKeyStore() throws SignerException {

    FileInputStream is = null;//from  w  ww.j  ava  2 s  .co m

    try {
        is = new FileInputStream(keyStoreFile);
    } catch (FileNotFoundException ex) {
        throw new SignerException("Could not find keystore", ex);
    }

    try {
        keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    } catch (KeyStoreException ex) {
        throw new SignerException("Could not instantiate keystore", ex);
    }

    char[] passwd = password.toCharArray();

    try {
        keyStore.load(is, passwd);
    } catch (IOException | NoSuchAlgorithmException | CertificateException ex) {
        throw new SignerException("Could not load keystore", ex);
    }

    close(is);
}

From source file:cz.cvut.jirutjak.fastimport.droid.utils.ExtraKeyStoreHttpClientFactory.java

protected SSLSocketFactory createAdditionalCertsSSLSocketFactory() {
    try {//w ww  .j a v a  2  s. com
        KeyStore keyStore = KeyStore.getInstance("BKS");

        // the bks file we generated above
        InputStream in = context.getResources().openRawResource(getKeyStoreResourceId());
        try {
            // don't forget to put the password used above in strings.xml/mystore_password
            keyStore.load(in, keyStorePassword.toCharArray());
        } finally {
            in.close();
        }

        return new AdditionalKeyStoresSSLSocketFactory(keyStore);

    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:inet.encode.SecureMonitor.java

private static void createHttpsServer() {
    try {// w  w w.  j ava2s.  c  o m
        server = HttpsServer.create(new InetSocketAddress(MONITOR_SERVER_PORT), 0);

        SSLContext sslContext = SSLContext.getInstance("TLS");
        // initialise the keystore
        char[] password = Encoder.KEY_STORE_PASS_PHRASE.toCharArray();
        KeyStore ks = KeyStore.getInstance("JKS");
        FileInputStream fis = new FileInputStream(Encoder.KEY_STORE_PATH);
        ks.load(fis, password);

        // setup the key manager factory
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ks, password);

        // setup the trust manager factory
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
        tmf.init(ks);

        // setup the HTTPS context and parameters
        sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

        server.setHttpsConfigurator(new HttpsConfigurator(sslContext));
        server.setExecutor(java.util.concurrent.Executors.newCachedThreadPool());
        server.start();
    } catch (Exception ex) {
        Logger.log(ex);
    }
}

From source file:com.microsoft.office.core.auth.AbstractAuthenticationFactory.java

/**
 * Creates HttpClient instance for given method and URI.
 *
 * @param method Http method./*from w ww  . ja v  a  2  s.  c  om*/
 * @param uri Target URI.
 * @return HttpClient instance prepared to make request.
 */
@SuppressWarnings("deprecation")
public HttpClient createHttpClient(HttpMethod method, URI uri) {
    HttpClient httpclient = super.createHttpClient(method, uri);

    final IAuthenticator creds = Configuration.getAuthenticator();
    if (creds != null) {
        creds.prepareClient(httpclient);
    }

    httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, getConnectionTimeout());
    httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, getSocketTimeout());

    if (Configuration.isTrustAll()) {
        try {
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(null, null);

            SSLSocketFactory sf = new TrustAllSSLSocketFactory(trustStore);
            sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            SchemeRegistry registry = new SchemeRegistry();
            registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
            registry.register(new Scheme("https", sf, 443));
            ClientConnectionManager ccm = new ThreadSafeClientConnManager(registry);
            httpclient = new DefaultHttpClient(ccm, httpclient.getParams());
        } catch (Exception e) {
        }
    }

    return httpclient;
}

From source file:com.enioka.jqm.tools.JettyTest.java

@Test
public void testSslServices() throws Exception {
    Helpers.setSingleParam("enableWsApiSsl", "true", em);
    Helpers.setSingleParam("disableWsApi", "false", em);
    Helpers.setSingleParam("enableWsApiAuth", "false", em);

    addAndStartEngine();//w ww .j a  v  a  2s .c  om

    // Launch a job so as to be able to query its status later
    CreationTools.createJobDef(null, true, "App", null, "jqm-tests/jqm-test-datetimemaven/target/test.jar",
            TestHelpers.qVip, 42, "MarsuApplication", null, "Franquin", "ModuleMachin", "other", "other", true,
            em);
    JobRequest j = new JobRequest("MarsuApplication", "TestUser");
    int i = JqmClientFactory.getClient().enqueue(j);
    TestHelpers.waitFor(1, 10000, em);

    // HTTPS client - with
    KeyStore trustStore = KeyStore.getInstance("JKS");
    FileInputStream instream = new FileInputStream(new File("./conf/trusted.jks"));
    try {
        trustStore.load(instream, "SuperPassword".toCharArray());
    } finally {
        instream.close();
    }

    SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore).build();
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);

    CloseableHttpClient cl = HttpClients.custom().setSSLSocketFactory(sslsf).build();

    int port = em.createQuery("SELECT q.port FROM Node q WHERE q.id = :i", Integer.class)
            .setParameter("i", TestHelpers.node.getId()).getSingleResult();
    HttpUriRequest rq = new HttpGet(
            "https://" + TestHelpers.node.getDns() + ":" + port + "/ws/simple/status?id=" + i);
    jqmlogger.debug(rq.getURI());
    CloseableHttpResponse rs = cl.execute(rq);
    Assert.assertEquals(200, rs.getStatusLine().getStatusCode());

    rs.close();
    cl.close();
}

From source file:com.supremainc.biostar2.sdk.volley.toolbox.HttpClientStack.java

public HttpClient getNewHttpClient() {
    try {//  w  w w . j a  va2s. co  m
        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);

        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) {
        return new DefaultHttpClient();
    }
}

From source file:org.elasticsearch.client.RestClientBuilderIntegTests.java

private static SSLContext getSslContext() throws Exception {
    SSLContext sslContext = SSLContext.getInstance("TLS");
    try (InputStream in = RestClientBuilderIntegTests.class.getResourceAsStream("/testks.jks")) {
        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(in, "password".toCharArray());
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(keyStore, "password".toCharArray());
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
        tmf.init(keyStore);//from ww  w  .  ja  va  2  s  .  co m
        sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    }
    return sslContext;
}