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.mama100.rs.client.RESTfulClient.java

public void callHttpClient() throws Exception {
    String keyStoreLoc = "clientKeystore.jks";

    KeyStore keyStore = KeyStore.getInstance("JKS");
    InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(keyStoreLoc);
    if (is == null) {
        System.out.println("--------------------can't get the resource file " + keyStoreLoc);
    }/* w  w  w .j  a v  a  2 s  .c o  m*/
    keyStore.load(is, "cspass".toCharArray());
    /*
     * Send HTTP GET request to query customer info using portable HttpClient
     * object from Apache HttpComponents
     */
    SSLSocketFactory sf = new SSLSocketFactory(keyStore, "ckpass", keyStore);
    Scheme httpsScheme = new Scheme("https", 9000, sf);

    System.out.println("Sending HTTPS GET request to query customer info");
    DefaultHttpClient httpclient = new DefaultHttpClient();
    httpclient.getConnectionManager().getSchemeRegistry().register(httpsScheme);
    HttpGet httpget = new HttpGet(BASE_SERVICE_URL + "/123");
    BasicHeader bh = new BasicHeader("Accept", "text/xml");
    httpget.addHeader(bh);

    HttpResponse response = httpclient.execute(httpget);
    System.out.println("-----" + response.getStatusLine().getStatusCode());
    HttpEntity entity = response.getEntity();
    entity.writeTo(System.out);
    httpclient.getConnectionManager().shutdown();
}

From source file:io.fabric8.utils.cxf.WebClients.java

public static KeyStore createTrustStore(String caCertData, File caCertFile) throws Exception {
    try (InputStream pemInputStream = getInputStreamFromDataOrFile(caCertData, caCertFile)) {
        CertificateFactory certFactory = CertificateFactory.getInstance("X509");
        X509Certificate cert = (X509Certificate) certFactory.generateCertificate(pemInputStream);

        KeyStore trustStore = KeyStore.getInstance("JKS");
        trustStore.load(null);//w w  w.  j a va2 s .  co  m

        String alias = cert.getSubjectX500Principal().getName();
        trustStore.setCertificateEntry(alias, cert);

        return trustStore;
    }
}

From source file:es.uja.photofirma.android.DoConnection.java

/**
 * // w  w w. java 2  s .co m
 * @return DefaultHttpClient(ccm, params)
 */
public HttpClient getNewHttpClient() {
    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);

        //aado timeout
        HttpConnectionParams.setConnectionTimeout(params, 6000); //timeout en establecer conexion
        HttpConnectionParams.setSoTimeout(params, 10000); //timeout en recibir respuesta

        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:edu.gmu.isa681.server.Server.java

/**
 * Creates a TLS server socket factory using the key store and key store password provided to the JVM at runtime.
 * @return/*from   ww w  .  ja  v a2 s .co  m*/
 * @throws GeneralSecurityException If an error occurs while creating the TLS factory.
 * @throws IOException If an error occurs while reading the key store.
 * 
 * Adapted from Oracle JSSE docs.
 */
private static SSLServerSocketFactory getSSLServerSocketFactory() throws GeneralSecurityException, IOException {
    FileInputStream fis = null;
    try {
        SSLServerSocketFactory ssf = null;
        // set up key manager to do server authentication
        SSLContext ctx = SSLContext.getInstance("TLS");
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        KeyStore ks = KeyStore.getInstance("JKS");

        String keyStore = System.getProperty("javax.net.ssl.keyStore");
        String keyStorePassword = System.getProperty("javax.net.ssl.keyStorePassword");

        fis = new FileInputStream(keyStore);
        ks.load(fis, keyStorePassword.toCharArray());

        kmf.init(ks, keyStorePassword.toCharArray());
        ctx.init(kmf.getKeyManagers(), null, null);

        ssf = ctx.getServerSocketFactory();
        return ssf;

    } finally {
        Utils.closeQuitely(fis);
    }
}

From source file:com.springcryptoutils.core.keystore.DefaultKeyStoreFactoryBean.java

public void afterPropertiesSet() throws KeyStoreException, IOException, NoSuchAlgorithmException,
        CertificateException, InitializationException {
    final String keyStoreLocation = System.getProperty("javax.net.ssl.keyStore");

    if (keyStoreLocation == null || keyStoreLocation.trim().length() == 0) {
        throw new InitializationException(
                "no value was specified for the system property: javax.net.ssl.keyStore");
    }/*from  ww w  . ja  va  2s .  c  o m*/

    final String password = System.getProperty("javax.net.ssl.keyStorePassword");
    final Resource location = new FileSystemResource(keyStoreLocation);
    keystore = KeyStore.getInstance("JKS");
    keystore.load(location.getInputStream(), password.toCharArray());
}

From source file:org.wso2.emm.agent.proxy.clients.OAuthSSLClient.java

@Override
public HttpClient getHttpClient() throws IDPTokenManagerException {
    HttpClient client = null;/*w w w .  j  a v  a2 s . co m*/
    InputStream inStream = null;
    try {
        if (Constants.SERVER_PROTOCOL.equalsIgnoreCase("https://")) {
            KeyStore localTrustStore = KeyStore.getInstance("BKS");
            inStream = IdentityProxy.getInstance().getContext().getResources().openRawResource(R.raw.trust);
            localTrustStore.load(inStream, Constants.TRUSTSTORE_PASSWORD.toCharArray());

            SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), Constants.HTTP));
            SSLSocketFactory sslSocketFactory = new SSLSocketFactory(localTrustStore);
            sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            schemeRegistry.register(new Scheme("https", sslSocketFactory, Constants.HTTPS));
            HttpParams params = new BasicHttpParams();
            ClientConnectionManager connectionManager = new ThreadSafeClientConnManager(params, schemeRegistry);

            client = new DefaultHttpClient(connectionManager, params);

        } else {
            client = new DefaultHttpClient();
        }

    } catch (KeyStoreException e) {
        String errorMsg = "Error occurred while accessing keystore.";
        Log.e(TAG, errorMsg);
        throw new IDPTokenManagerException(errorMsg, e);
    } catch (CertificateException e) {
        String errorMsg = "Error occurred while loading certificate.";
        Log.e(TAG, errorMsg);
        throw new IDPTokenManagerException(errorMsg, e);
    } catch (NoSuchAlgorithmException e) {
        String errorMsg = "Error occurred while due to mismatch of defined algorithm.";
        Log.e(TAG, errorMsg);
        throw new IDPTokenManagerException(errorMsg, e);
    } catch (UnrecoverableKeyException e) {
        String errorMsg = "Error occurred while accessing keystore.";
        Log.e(TAG, errorMsg);
        throw new IDPTokenManagerException(errorMsg, e);
    } catch (KeyManagementException e) {
        String errorMsg = "Error occurred while accessing keystore.";
        Log.e(TAG, errorMsg);
        throw new IDPTokenManagerException(errorMsg, e);
    } catch (IOException e) {
        String errorMsg = "Error occurred while loading trust store. ";
        Log.e(TAG, errorMsg);
        throw new IDPTokenManagerException(errorMsg, e);
    } finally {
        StreamHandlerUtil.closeInputStream(inStream, TAG);
    }
    return client;
}

From source file:com.tvs.signaltracker.Utils.java

public static HttpClient getNewHttpClient() {
    try {//from w w w  . ja v  a2  s.  c o m
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new EasySSLSocketFactory(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:de.geeksfactory.opacclient.networking.HTTPClient.java

public static HttpClient getNewHttpClient(boolean customssl, boolean disguise_app) {
    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setRedirectStrategy(new CustomRedirectStrategy());
    if (disguise_app) {
        builder.setUserAgent("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, "
                + "like Gecko) Chrome/43.0.2357.130 Safari/537.36\t");
    } else {/* w  ww .j ava2s  .  c  o m*/
        builder.setUserAgent("OpacApp/" + OpacClient.versionName);
    }
    if (customssl) {
        try {
            if (trustStore == null) {
                trustStore = KeyStore.getInstance("BKS");
                final InputStream in = OpacClient.context.getResources().openRawResource(R.raw.ssl_trust_store);
                try {
                    trustStore.load(in, "ro5eivoijeeGohsh0daequoo5Zeepaen".toCharArray());
                } finally {
                    in.close();
                }
            }

            ConnectionSocketFactory sf = AdditionalKeyStoresSSLSocketFactory.create(trustStore);

            Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sf)
                    .build();

            HttpClientConnectionManager ccm = new PoolingHttpClientConnectionManager(registry);
            builder.setConnectionManager(ccm);

            return builder.build();
        } catch (Exception e) {
            e.printStackTrace();
            return builder.build();
        }
    } else {
        return builder.build();
    }
}

From source file:com.vtc.basetube.services.volley.ssl.EasySSLSocketFactory.java

private static SSLContext createEasySSLContext(Context context) throws IOException {
    try {//from  w w  w .j av  a  2  s. c  o m
        // Client should authenticate itself with the valid certificate to
        // Server.
        InputStream clientStream = context.getResources().openRawResource(CERTIFICATE_RESOURCE_CLIENT);
        char[] password = "XXXXXXXXXXXXX".toCharArray();

        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        keyStore.load(clientStream, password);

        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, password);

        // Client should also add the CA certificate obtained from server
        // and create TrustManager from it for the client to validate the
        // identity of the server.
        KeyStore trustStore = KeyStore.getInstance("BKS");
        InputStream instream = null;
        instream = context.getResources().openRawResource(CERTIFICATE_RESOURCE_CA);

        try {
            trustStore.load(instream, "XXXXXXXX".toCharArray());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                instream.close();
            } catch (Exception ignore) {
            }
        }

        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init(trustStore);

        // Create an SSLContext that uses our TrustManager & Keystore
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagerFactory.getKeyManagers(), tmf.getTrustManagers(), null);

        return sslContext;
    } catch (Exception e) {
        e.printStackTrace();
        throw new IOException(e.getMessage());
    }
}

From source file:Main.java

/**
 * Returns the local store of reliable server certificates, explicitly accepted by the user.
 * /*ww w . ja v a2s.  c om*/
 * Returns a KeyStore instance with empty content if the local store was never created.
 * 
 * Loads the store from the storage environment if needed.
 * 
 * @param context                       Android context where the operation is being performed.
 * @return                              KeyStore instance with explicitly-accepted server certificates. 
 * @throws KeyStoreException            When the KeyStore instance could not be created.
 * @throws IOException                  When an existing local trust store could not be loaded.
 * @throws NoSuchAlgorithmException     When the existing local trust store was saved with an unsupported algorithm.
 * @throws CertificateException         When an exception occurred while loading the certificates from the local trust store.
 */
private static KeyStore getKnownServersStore(Context context)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {
    if (mKnownServersStore == null) {
        //mKnownServersStore = KeyStore.getInstance("BKS");
        mKnownServersStore = KeyStore.getInstance(KeyStore.getDefaultType());
        File localTrustStoreFile = new File(context.getFilesDir(), LOCAL_TRUSTSTORE_FILENAME);
        Log.d(TAG, "Searching known-servers store at " + localTrustStoreFile.getAbsolutePath());
        if (localTrustStoreFile.exists()) {
            InputStream in = new FileInputStream(localTrustStoreFile);
            try {
                mKnownServersStore.load(in, LOCAL_TRUSTSTORE_PASSWORD.toCharArray());
            } finally {
                in.close();
            }
        } else {
            mKnownServersStore.load(null, LOCAL_TRUSTSTORE_PASSWORD.toCharArray()); // necessary to initialize an empty KeyStore instance
        }
    }
    return mKnownServersStore;
}