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.yodlee.sampleapps.helper.OpenSamlHelper.java

/**
 * Initilize the Keystore./*from  w w  w .ja v a  2  s.  c o  m*/
 */
private static void initKeyStore() {
    InputStream fileInput = null;
    try {
        fileInput = new FileInputStream(keystoreFilename);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        throw new RuntimeException(e.getMessage());
    }
    KeyStore keystore = null;
    try {
        keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        keystore.load(fileInput, keystorePassword.toCharArray());
        privateKey = (PrivateKey) keystore.getKey(keystoreAlias, keystorePassword.toCharArray());
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e.getMessage());
    }

    if (privateKey == null)
        throw new RuntimeException(keystoreAlias + " key not found in keystore " + keystoreFilename);

    X509Certificate cert = null;
    Certificate[] certificates = new Certificate[0];
    try {
        cert = (X509Certificate) keystore.getCertificate(keystoreAlias);
        certificates = keystore.getCertificateChain(keystoreAlias);
    } catch (KeyStoreException e) {
        e.printStackTrace();
        throw new RuntimeException(e.getMessage());
    }
    if (cert == null)
        throw new RuntimeException(keystoreAlias + " cert not found in keystore " + keystoreFilename);

    if (certificates == null)
        throw new RuntimeException(keystoreAlias + " cert chain not found in keystore " + keystoreFilename);

    certs = new X509Certificate[certificates.length];
    System.arraycopy(certificates, 0, certs, 0, certs.length);
}

From source file:nl.surfnet.spring.security.opensaml.CertificateStoreImpl.java

public void afterPropertiesSet() throws Exception {
    keystorePassword = "secret";
    try {//www .  j av a2  s.c om
        keyStore = KeyStore.getInstance("JKS");
        keyStore.load(null, keystorePassword.toCharArray());
        for (Map.Entry<String, String> entry : certificates.entrySet()) {
            appendToKeyStore(entry.getKey(), entry.getValue());
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.wso2telco.identity.application.authentication.endpoint.util.MutualSSLClient.java

/**
 * load key store with given keystore.jks
 *
 * @param keyStorePath/*from   w w  w  . jav a  2 s  . c  o  m*/
 * @param keyStorePassoword
 * @throws java.security.KeyStoreException
 * @throws java.io.IOException
 * @throws java.security.cert.CertificateException
 * @throws java.security.NoSuchAlgorithmException
 */
public static void loadKeyStore(String keyStorePath, String keyStorePassoword)
        throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException {
    keyStorePassword = keyStorePassoword;
    keyStore = KeyStore.getInstance(KEY_STORE_TYPE);
    keyStore.load(new FileInputStream(keyStorePath), keyStorePassoword.toCharArray());
}

From source file:org.anhonesteffort.flock.registration.HttpClientFactory.java

public DefaultHttpClient buildClient() throws RegistrationApiException {
    try {/*  ww w  .  j  a v  a 2  s  . co  m*/

        AssetManager assetManager = context.getAssets();
        InputStream keyStoreInputStream = assetManager.open("flock.store");
        KeyStore trustStore = KeyStore.getInstance("BKS");

        trustStore.load(keyStoreInputStream, "owsflock".toCharArray());

        SSLSocketFactory appSSLSocketFactory = new SSLSocketFactory(trustStore);
        DefaultHttpClient client = new DefaultHttpClient();
        SchemeRegistry schemeRegistry = client.getConnectionManager().getSchemeRegistry();
        Scheme httpsScheme = new Scheme("https", appSSLSocketFactory, 443);

        schemeRegistry.register(httpsScheme);

        return client;

    } catch (Exception e) {
        Log.e(getClass().getName(), "caught exception while constructing HttpClient client", e);
        throw new RegistrationApiException(
                "caught exception while constructing HttpClient client: " + e.toString());
    }
}

From source file:com.wudaosoft.net.httpclient.SSLContextBuilder.java

public SSLContext buildPKCS12() {

    Args.notEmpty(password, "password");
    Args.notNull(cert, "cert");

    char[] pwd = password.toCharArray();

    try {/*from  w w w.j a  v a 2  s.  com*/
        KeyStore ks = KeyStore.getInstance("PKCS12");

        ks.load(cert.openStream(), pwd);

        //  & ?
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(ks, pwd);

        //  SSLContext
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(kmf.getKeyManagers(), null, new SecureRandom());

        return sslContext;
    } catch (Exception e) {
        if (e instanceof RuntimeException)
            throw (RuntimeException) e;
        throw new RuntimeException(e);
    }
}

From source file:org.changhong.sync.web.MySSLSocketFactory.java

public static DefaultHttpClient getNewHttpClient() {
    try {//  www  . j  av  a2s  .  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:com.example.froyoandwams.FroyoSupport.java

private static SSLSocketFactory createAdditionalCertsSSLSocketFactory() {
    try {//from   www.  ja  v  a 2s  . c om
        final KeyStore ks = KeyStore.getInstance("BKS");

        Activity mainActivity = MainActivity.getInstance();
        final InputStream in = mainActivity.getResources().openRawResource(R.raw.mobileservicestore);
        try {
            ks.load(in, "mobileservices".toCharArray());
        } finally {
            in.close();
        }

        return new AdditionalKeyStoresSSLSocketFactory(ks);

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

From source file:com.lonepulse.travisjr.net.ZombieConfig.java

@Override
public HttpClient httpClient() {

    HttpClient client = super.httpClient();

    try {//from   www  . j a v a2 s .c o m

        KeyStore keyStore = KeyStore.getInstance("BKS");
        InputStream is = TravisJr.Application.getContext().getResources().openRawResource(R.raw.travisjr);

        try {

            keyStore.load(is, null);
        } finally {

            is.close();
        }

        SSLSocketFactory sslSocketFactory = new SSLSocketFactory(keyStore);
        sslSocketFactory.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);

        SchemeRegistry schemeRegistry = ((ThreadSafeClientConnManager) client.getConnectionManager())
                .getSchemeRegistry();

        schemeRegistry.register(new Scheme("https", sslSocketFactory, 443));
    } catch (Exception e) {

        Log.e(getClass().getSimpleName(), "HttpClient configuration with a custom SSLSocketFactory failed.", e);
    }

    return client;
}

From source file:br.gov.frameworkdemoiselle.behave.integration.alm.httpsclient.HttpsClient.java

public static HttpClient getNewHttpClient(String encoding) {
    try {//w  ww.  j  a  v a  2s.  com
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        MySSLSocketFactory sf = new MySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

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

        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:net.di2e.ecdr.source.rest.TLSUtil.java

public static void setTLSOptions(WebClient client, boolean disableCNCheck) {
    ClientConfiguration clientConfiguration = WebClient.getConfig(client);

    HTTPConduit httpConduit = clientConfiguration.getHttpConduit();

    String keyStorePath = System.getProperty(SSL_KEYSTORE_JAVA_PROPERTY);
    String keyStorePassword = System.getProperty(SSL_KEYSTORE_PASSWORD_JAVA_PROPERTY);
    if (StringUtils.isNotBlank(keyStorePath) && StringUtils.isNotBlank(keyStorePassword)) {
        try {//from  w  ww . j  a va2s.c om
            TLSClientParameters tlsParams = new TLSClientParameters();
            LOGGER.debug("Setting disable of CN check on client URL {} to [{}]", client.getCurrentURI(),
                    disableCNCheck);
            tlsParams.setDisableCNCheck(disableCNCheck);

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

            // add the keystore if it exists
            File keystore = new File(keyStorePath);
            if (keystore.exists() && keyStorePassword != null) {
                FileInputStream fis = new FileInputStream(keystore);
                try {
                    LOGGER.debug("Loading keyStore {}", keystore);
                    keyStore.load(fis, keyStorePassword.toCharArray());
                } catch (IOException e) {
                    LOGGER.error("Unable to load keystore. {}", keystore, e);
                } catch (CertificateException e) {
                    LOGGER.error("Unable to load certificates from keystore. {}", keystore, e);
                } finally {
                    IOUtils.closeQuietly(fis);
                }
                KeyManagerFactory keyFactory = KeyManagerFactory
                        .getInstance(KeyManagerFactory.getDefaultAlgorithm());
                keyFactory.init(keyStore, keyStorePassword.toCharArray());
                KeyManager[] km = keyFactory.getKeyManagers();
                tlsParams.setKeyManagers(km);
            }

            httpConduit.setTlsClientParameters(tlsParams);
        } catch (KeyStoreException e) {
            LOGGER.error("Unable to read keystore: ", e);
        } catch (NoSuchAlgorithmException e) {
            LOGGER.error("Problems creating SSL socket. Usually this is "
                    + "referring to the certificate sent by the server not being trusted by the client.", e);
        } catch (FileNotFoundException e) {
            LOGGER.error("Unable to locate one of the SSL stores: {} | {}", keyStorePath, e);
        } catch (UnrecoverableKeyException e) {
            LOGGER.error("Unable to read keystore: ", e);
        }
    }
}