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:org.springframework.cloud.vault.ClientHttpRequestFactoryFactory.java

private static TrustManagerFactory createTrustManagerFactory(Resource trustFile, String storePassword)
        throws GeneralSecurityException, IOException {

    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());

    try (InputStream inputStream = trustFile.getInputStream()) {
        trustStore.load(inputStream, StringUtils.hasText(storePassword) ? storePassword.toCharArray() : null);
    }//w ww.  jav a 2  s.c o m

    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(trustStore);

    return trustManagerFactory;
}

From source file:com.cloudbees.eclipse.core.util.Utils.java

/**
 * @param url/*w  ww . ja  v  a2  s  .  c o m*/
 *          url to connec. Required to determine proxy settings if available. If <code>null</code> then proxy is not
 *          configured for the client returned.
 * @return
 * @throws CloudBeesException
 */
public final static DefaultHttpClient getAPIClient(String url) throws CloudBeesException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {
        HttpClientParams.setCookiePolicy(httpclient.getParams(), CookiePolicy.BROWSER_COMPATIBILITY);

        String version = null;
        if (CloudBeesCorePlugin.getDefault() != null) {
            version = CloudBeesCorePlugin.getDefault().getBundle().getVersion().toString();
        } else {
            version = "n/a";
        }
        HttpProtocolParams.setUserAgent(httpclient.getParams(), "CBEclipseToolkit/" + version);

        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());

        CloudBeesCorePlugin plugin = CloudBeesCorePlugin.getDefault();

        URL truststore;

        if (plugin == null) {
            //Outside the OSGI environment, try to open the stream from the current dir.
            truststore = new File("truststore").toURI().toURL();
        } else {
            truststore = plugin.getBundle().getResource("truststore");
        }

        InputStream instream = truststore.openStream();

        try {
            trustStore.load(instream, "123456".toCharArray());
        } finally {
            instream.close();
        }

        TrustStrategy trustAllStrategy = new TrustStrategy() {
            @Override
            public boolean isTrusted(final X509Certificate[] chain, final String authType)
                    throws CertificateException {
                return true;
            }
        };

        SSLSocketFactory socketFactory = new SSLSocketFactory(SSLSocketFactory.TLS, null, null, trustStore,
                null, trustAllStrategy, SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        // Override https handling to use provided truststore
        @SuppressWarnings("deprecation")
        Scheme sch = new Scheme("https", socketFactory, 443);
        httpclient.getConnectionManager().getSchemeRegistry().register(sch);

        HttpParams params = httpclient.getParams();

        //TODO Make configurable from the UI?
        HttpConnectionParams.setConnectionTimeout(params, 10000);
        HttpConnectionParams.setSoTimeout(params, 10000);

        if (CloudBeesCorePlugin.getDefault() != null) { // exclude proxy support when running outside eclipse
            IProxyService ps = CloudBeesCorePlugin.getDefault().getProxyService();
            if (ps.isProxiesEnabled()) {

                IProxyData[] pr = ps.select(new URI(url));

                //NOTE! For now we use just the first proxy settings with type HTTP or HTTPS to try out the connection. If configuration has more than 1 conf then for now this likely won't work!
                if (pr != null) {
                    for (int i = 0; i < pr.length; i++) {

                        IProxyData prd = pr[i];

                        if (IProxyData.HTTP_PROXY_TYPE.equals(prd.getType())
                                || IProxyData.HTTPS_PROXY_TYPE.equals(prd.getType())) {

                            String proxyHost = prd.getHost();
                            int proxyPort = prd.getPort();
                            String proxyUser = prd.getUserId();
                            String proxyPass = prd.getPassword();

                            HttpHost proxy = new HttpHost(proxyHost, proxyPort);
                            httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

                            if (prd.isRequiresAuthentication()) {
                                List authpref = new ArrayList();
                                authpref.add(AuthPolicy.BASIC);
                                AuthScope authScope = new AuthScope(proxyHost, proxyPort);
                                httpclient.getCredentialsProvider().setCredentials(authScope,
                                        new UsernamePasswordCredentials(proxyUser, proxyPass));
                            }

                            break;

                        }

                    }
                }
            }
        }

        /*      httpclient.getHostConfiguration().setProxy(proxyHost,proxyPort);      
              //if there are proxy credentials available, set those too
              Credentials proxyCredentials = null;
              String proxyUser = beesClientConfiguration.getProxyUser();
              String proxyPassword = beesClientConfiguration.getProxyPassword();
              if(proxyUser != null || proxyPassword != null)
        proxyCredentials = new UsernamePasswordCredentials(proxyUser, proxyPassword);
              if(proxyCredentials != null)
        client.getState().setProxyCredentials(AuthScope.ANY, proxyCredentials);
                
        */

        return httpclient;

    } catch (Exception e) {
        throw new CloudBeesException("Error while initiating access to JSON APIs!", e);
    }
}

From source file:com.cwctravel.plugins.jenkins.trustcredentials.TrustCredentialsImpl.java

public KeyStore getTrustStore() {
    long lastModified = trustStoreSource.getTrustStoreLastModified();
    if (trustStore == null || trustStoreLastModified < lastModified) {
        KeyStore keyStore;/*from  ww w. j  a va 2s.c  o m*/
        try {
            keyStore = KeyStore.getInstance("JKS");
        } catch (KeyStoreException e) {
            throw new IllegalStateException("JKS is a trustStore type per the JLS spec", e);
        }
        try {
            keyStore.load(new ByteArrayInputStream(trustStoreSource.getTrustStoreBytes()),
                    toCharArray(password));
        } catch (CertificateException e) {
            LOGGER.log(Level.WARNING, "Could not load trustStore from " + trustStoreSource.toString(), e);
        } catch (NoSuchAlgorithmException e) {
            LOGGER.log(Level.WARNING, "Could not load trustStore from " + trustStoreSource.toString(), e);
        } catch (IOException e) {
            LOGGER.log(Level.WARNING, "Could not load trustStore from " + trustStoreSource.toString(), e);
        }
        this.trustStore = keyStore;
        this.trustStoreLastModified = lastModified;
    }
    return trustStore;
}

From source file:org.wso2.carbon.esb.rabbitmq.message.store.jira.ESBJAVA4569RabbiMQSSLStoreWithClientCertValidationTest.java

/**
 * Helper method to retrieve queue message from rabbitMQ
 *
 * @return result//w  w  w  . ja v  a  2s .c o  m
 * @throws Exception
 */
private static String consumeWithoutCertificate() throws Exception {
    String result = "";

    String basePath = TestConfigurationProvider.getResourceLocation()
            + "/artifacts/ESB/messageStore/rabbitMQ/SSL/";

    String truststoreLocation = basePath + "rabbitMQ/certs/client/rabbitstore";
    String keystoreLocation = basePath + "rabbitMQ/certs/client/keycert.p12";

    char[] keyPassphrase = "MySecretPassword".toCharArray();
    KeyStore ks = KeyStore.getInstance("PKCS12");
    ks.load(new FileInputStream(keystoreLocation), keyPassphrase);

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(ks, keyPassphrase);

    char[] trustPassphrase = "rabbitstore".toCharArray();
    KeyStore tks = KeyStore.getInstance("JKS");
    tks.load(new FileInputStream(truststoreLocation), trustPassphrase);

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    tmf.init(tks);

    SSLContext c = SSLContext.getInstance("SSL");
    c.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    factory.setPort(5671);
    factory.useSslProtocol(c);

    Connection conn = factory.newConnection();
    Channel channel = conn.createChannel();

    GetResponse chResponse = channel.basicGet("WithClientCertQueue", true);
    if (chResponse != null) {
        byte[] body = chResponse.getBody();
        result = new String(body);
    }
    channel.close();
    conn.close();
    return result;
}

From source file:module.signature.util.XAdESValidator.java

private static void loadNeededCerts() {

    try {// w ww  . j a v a2  s  .c o  m
        InputStream keyStoreIS = XAdESValidator.class.getResourceAsStream("/resources/certs/cc-keystore");
        cartaoCidadaoKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        cartaoCidadaoKeyStore.load(keyStoreIS, "123456".toCharArray());

        InputStream tsaCertIS = XAdESValidator.class.getResourceAsStream("/resources/certs/tsaCert.cer");

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        while (tsaCertIS.available() != 0) {
            //not the fastest way to do it.. but who cares 
            baos.write(tsaCertIS.read());
        }
        tsaCert = new X509CertificateHolder(baos.toByteArray());

    } catch (KeyStoreException e) {
        logger.error("Error loading the needed certificates", e);
    } catch (NoSuchAlgorithmException e) {
        logger.error("Error loading the needed certificates", e);
    } catch (CertificateException e) {
        logger.error("Error loading the needed certificates", e);
    } catch (IOException e) {
        logger.error("Error loading the needed certificates", e);
    }
}

From source file:be.fedict.hsm.model.KeyStoreLoaderBean.java

private Map<String, PrivateKeyEntry> loadPKCS12(KeyStoreEntity keyStoreEntity) throws KeyStoreException,
        NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableEntryException {
    String keyStorePath = keyStoreEntity.getPath();
    InputStream keyStoreInputStream = new FileInputStream(keyStorePath);
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    String keyStorePassword = keyStoreEntity.getPassword();
    keyStore.load(keyStoreInputStream, keyStorePassword.toCharArray());
    return loadKeys(keyStoreEntity, keyStore, keyStorePassword);
}

From source file:org.mitre.svmp.net.SSLConfig.java

@SuppressLint("TrulyRandom")
private void doConfigure() throws KeyStoreException, CertificateException, NoSuchAlgorithmException,
        IOException, KeyManagementException {
    // find out if we should use the MemorizingTrustManager instead of the system trust store (set in Preferences)
    boolean useMTM = Utility.getPrefBool(context, R.string.preferenceKey_connection_useMTM,
            R.string.preferenceValue_connection_useMTM);

    // determine whether we should use client certificate authentication
    boolean useCertificateAuth = Constants.API_14 && (connectionInfo.getAuthType()
            & CertificateModule.AUTH_MODULE_ID) == CertificateModule.AUTH_MODULE_ID;

    // set up key managers
    KeyManager[] keyManagers = null;
    // if certificate authentication is enabled, use a key manager with the provided alias
    if (useCertificateAuth) {
        keyManagers = new KeyManager[] { new SVMPKeyManager(context, connectionInfo.getCertificateAlias()) };
    }/*from ww w .  jav  a  2 s  .c om*/

    // set up trust managers
    TrustManager[] trustManagers = null;

    KeyStore localTrustStore = KeyStore.getInstance("BKS");
    InputStream in = context.getResources().openRawResource(R.raw.client_truststore);
    localTrustStore.load(in, Constants.TRUSTSTORE_PASSWORD.toCharArray());
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(localTrustStore);

    // 1) If "res/raw/client_truststore.bks" is not empty, use it as the pinned cert trust store (default is empty)
    // 2) Otherwise, if the "Show certificate dialog" developer preference is enabled, use that (default is disabled)
    // 3) Otherwise, use the default system trust store, consists of normal trusted Android CA certs
    if (localTrustStore.size() > 0) {
        // this means that "res/raw/client_truststore.bks" has been replaced with a trust store that is not empty
        // we will use that "pinned" store to check server certificate trust
        Log.d(TAG, "SSLConfig: Using static BKS trust store to check server cert trust");
        trustManagers = trustManagerFactory.getTrustManagers();
        // After switching to WebSockets, MTM causes the app to freeze; removed for now
    } else if (useMTM) {
        // by default useMTM is false ("Show certificate dialog" in developer preferences)
        // this creates a certificate dialog to decide what to do with untrusted certificates, instead of flat-out rejecting them
        Log.d(TAG,
                "SSLConfig: Static BKS trust store is empty but MTM is enabled, using MTM to check server cert trust");
        mtm = new MemorizingTrustManager(context);
        mtm.bindDisplayActivity(activity);
        trustManagers = new X509TrustManager[] { mtm };
    } else {
        Log.d(TAG,
                "SSLConfig: Static BKS trust store is empty and MTM is disabled, using system trust store to check server cert trust");
        // leaving trustManagers null accomplishes this
    }

    PRNGFixes.apply(); // fix Android SecureRandom issue on pre-KitKat platforms
    sslContext = SSLContext.getInstance("TLS");
    sslContext.init(keyManagers, trustManagers, new SecureRandom());
}

From source file:com.codingPower.framework.worker.FileNetWorker.java

/**
 * ?httpClient/* www.  j  av  a  2s .c  o  m*/
 * @return
 */
protected HttpClient getHttpClient() {

    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);

        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:com.thoughtworks.go.security.KeyStoreManager.java

@Deprecated // Need to move the logic into this class so we don't have to touch the KeyStore in our code
public KeyStore load(File keystoreFile, String password) throws Exception {
    FileInputStream inputStream = null;
    try {//from  w  w  w. j a va  2 s .  c o  m
        KeyStore store = KeyStore.getInstance(KEYSTORE_TYPE);
        inputStream = maybeInputStream(keystoreFile);
        store.load(inputStream, maybePassword(password));
        return store;
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}

From source file:org.craftercms.commons.crypto.impl.SecretKeyRepositoryImpl.java

protected void loadKeyStore() throws CryptoException {
    try {//from   ww w  .  j a  va 2  s  .c  om
        keyStore = KeyStore.getInstance(KEY_STORE_TYPE);

        if (keyStoreFile.exists()) {
            try (InputStream in = new FileInputStream(keyStoreFile)) {
                keyStore.load(in, keyStorePassword);
            }

            logger.debug(LOG_KEY_KEY_STORE_LOADED, keyStoreFile);
        } else {
            // Create new empty keystore
            keyStore.load(null, keyStorePassword);
        }
    } catch (GeneralSecurityException | IOException e) {
        throw new CryptoException(ERROR_KEY_KEY_STORE_LOAD_ERROR, e);
    }
}