Example usage for java.security KeyStore getDefaultType

List of usage examples for java.security KeyStore getDefaultType

Introduction

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

Prototype

public static final String getDefaultType() 

Source Link

Document

Returns the default keystore type as specified by the keystore.type security property, or the string "jks" (acronym for "Java keystore" ) if no such property exists.

Usage

From source file:de.cellular.lib.lightlib.backend.LLRequest.java

/**
 * Creates a {@link DefaultHttpClient} object.
 * //from   w  w  w  . j  ava2s  .  co m
 * @since 1.0
 * @param _credsProvider
 *            the object contains connect credential info like: User, Pwd, Host etc.
 * @param _ALLOW_ALL_HOSTNAME_VERIFIER_FOR_SSL
 *            true allow all hostname verifier for ssl.
 * @return the {@link DefaultHttpClient} object
 */
public static DefaultHttpClient createHttpClient(CredentialsProvider _credsProvider,
        boolean _ALLOW_ALL_HOSTNAME_VERIFIER_FOR_SSL) {
    // -------------------------------------------------------------------
    // Example for _credsProvider
    //
    // String usr = getUser();
    // String pwd = getPassword();
    // DefaultHttpClient httpclient = new DefaultHttpClient(conMgr, params);
    // CredentialsProvider credsProvider = new BasicCredentialsProvider();
    // credsProvider.setCredentials(new AuthScope(host, port), new UsernamePasswordCredentials(usr, pwd));
    // -------------------------------------------------------------------

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

    SchemeRegistry schReg = new SchemeRegistry();
    PlainSocketFactory plainSocketFactory = PlainSocketFactory.getSocketFactory();
    SSLSocketFactory sslSocketFactory = null;

    if (_ALLOW_ALL_HOSTNAME_VERIFIER_FOR_SSL) {
        try {
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(null, null);
            sslSocketFactory = new EasySSLSocketFactory(trustStore);
        } catch (Exception _e) {
            LL.e(_e.toString());
            sslSocketFactory = SSLSocketFactory.getSocketFactory();
        }
        sslSocketFactory
                .setHostnameVerifier(org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } else {
        sslSocketFactory = SSLSocketFactory.getSocketFactory();
    }
    schReg.register(new Scheme("http", plainSocketFactory, 80));
    schReg.register(new Scheme("https", sslSocketFactory, 443));
    ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);

    DefaultHttpClient httpclient = new DefaultHttpClient(conMgr, params);
    if (_credsProvider != null) {
        httpclient.setCredentialsProvider(_credsProvider);
    }
    return httpclient;
}

From source file:org.hawkular.client.core.jaxrs.RestFactory.java

private HttpClient getHttpClient() {
    CloseableHttpClient httpclient = null;

    try {/*ww  w. ja  v  a2 s .  c o  m*/
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(keyStore, (TrustStrategy) (trustedCert, nameConstraints) -> true);

        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
        httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
        _logger.error("Failed to create HTTPClient: {}", e);
    }

    return httpclient;
}

From source file:org.gameontext.map.auth.PlayerClient.java

/**
 * Obtain the key we'll use to sign the jwts we use to talk to Player endpoints.
 *
 * @throws IOException//from  w  ww .  j  av a  2 s  .c o m
 *             if there are any issues with the keystore processing.
 */
private synchronized void getKeyStoreInfo() {
    try {
        // load up the keystore..
        FileInputStream is = new FileInputStream(keyStore);
        KeyStore signingKeystore = KeyStore.getInstance(KeyStore.getDefaultType());
        signingKeystore.load(is, keyStorePW.toCharArray());

        // grab the key we'll use to sign
        signingKey = signingKeystore.getKey(keyStoreAlias, keyStorePW.toCharArray());

    } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | UnrecoverableKeyException
            | IOException e) {
        throw new IllegalStateException("Unable to get required keystore: " + keyStore, e);
    }
}

From source file:com.aware.ui.Plugins_Manager.java

/**
* Downloads and compresses image for optimized icon caching
* @param image_url/* w w  w  .  j a  va2s .  c  o m*/
* @return
*/
public static byte[] cacheImage(String image_url, Context sContext) {
    try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        InputStream caInput = sContext.getResources().openRawResource(R.raw.aware);
        Certificate ca;
        try {
            ca = cf.generateCertificate(caInput);
        } finally {
            caInput.close();
        }

        KeyStore sKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        InputStream inStream = sContext.getResources().openRawResource(R.raw.awareframework);
        sKeyStore.load(inStream, "awareframework".toCharArray());
        inStream.close();

        sKeyStore.setCertificateEntry("ca", ca);

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

        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, tmf.getTrustManagers(), null);

        //Fetch image now that we recognise SSL
        URL image_path = new URL(image_url.replace("http://", "https://")); //make sure we are fetching the images over https
        HttpsURLConnection image_connection = (HttpsURLConnection) image_path.openConnection();
        image_connection.setSSLSocketFactory(context.getSocketFactory());

        InputStream in_stream = image_connection.getInputStream();
        Bitmap tmpBitmap = BitmapFactory.decodeStream(in_stream);
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        tmpBitmap.compress(Bitmap.CompressFormat.PNG, 100, output);

        return output.toByteArray();

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.springframework.vault.config.ClientHttpRequestFactoryFactory.java

private static KeyManagerFactory createKeyManagerFactory(Resource keystoreFile, String storePassword)
        throws GeneralSecurityException, IOException {

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

    loadKeyStore(keystoreFile, storePassword, keyStore);

    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore,//w  w w  . j av  a  2s. c o m
            StringUtils.hasText(storePassword) ? storePassword.toCharArray() : new char[0]);

    return keyManagerFactory;
}

From source file:org.ocsinventoryng.android.actions.OCSProtocol.java

public DefaultHttpClient getNewHttpClient(boolean strict) {
    try {/* w  w w  .j av  a 2s . co  m*/
        SSLSocketFactory sf;
        if (strict) {
            sf = SSLSocketFactory.getSocketFactory();
        } else {
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(null, null);
            sf = new CoolSSLSocketFactory(trustStore);
        }

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

        HttpConnectionParams.setConnectionTimeout(params, 10000);
        HttpConnectionParams.setSoTimeout(params, 10000);

        return new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}

From source file:com.geekandroid.sdk.pay.utils.Util.java

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

        SSLSocketFactory sf = new SSLSocketFactoryEx(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.eviware.soapui.impl.wsdl.support.http.SoapUISSLSocketFactory.java

@Override
public Socket createSocket(HttpParams params) throws IOException {
    String sslConfig = (String) params.getParameter(SoapUIHttpRoute.SOAPUI_SSL_CONFIG);

    if (StringUtils.isNullOrEmpty(sslConfig)) {
        return enableSocket((SSLSocket) sslContext.getSocketFactory().createSocket());
    }/*from  w ww  . j  av  a  2 s .c  om*/

    SSLSocketFactory factory = factoryMap.get(sslConfig);

    if (factory != null) {
        if (factory == this)
            return enableSocket((SSLSocket) sslContext.getSocketFactory().createSocket());
        else
            return enableSocket((SSLSocket) factory.createSocket(params));
    }

    try {
        // try to create new factory for specified config
        int ix = sslConfig.lastIndexOf(' ');
        String keyStore = sslConfig.substring(0, ix);
        String pwd = sslConfig.substring(ix + 1);

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

        if (keyStore.trim().length() > 0) {
            File f = new File(keyStore);

            if (f.exists()) {
                log.info("Initializing Keystore from [" + keyStore + "]");

                try {
                    KeyMaterial km = new KeyMaterial(f, pwd.toCharArray());
                    ks = km.getKeyStore();
                } catch (Exception e) {
                    SoapUI.logError(e);
                    pwd = null;
                }
            }
        }

        factory = new SoapUISSLSocketFactory(ks, pwd);
        factoryMap.put(sslConfig, factory);

        return enableSocket((SSLSocket) factory.createSocket(params));
    } catch (Exception gse) {
        SoapUI.logError(gse);
        return enableSocket((SSLSocket) super.createSocket(params));
    }
}

From source file:eu.eubrazilcc.lvl.core.http.client.TrustedHttpsClient.java

/**
 * Creates a custom SSL context where clients will trust own CA and self-signed certificates and associates a HTTP client to the context.
 * @return a HTTP client that will trust own CA and self-signed certificates.
 * @throws Exception if an error occurs.
 *//*from  w  ww .j  a  va 2  s .c  o m*/
private static final CloseableHttpClient createHttpClient(final File trustStoreDir, final char[] password,
        final String url) {
    CloseableHttpClient httpClient = null;
    try {
        final File trustStoreFile = new File(trustStoreDir, "trusted.keystore");
        final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        // create a new, empty trust store
        if (!trustStoreFile.exists()) {
            trustStoreDir.mkdirs();
            trustStoreFile.createNewFile();
            trustStore.load(null, password);

        }
        // import certificate to trust store
        importCertificate(url, trustStore);
        // save trust store to disk
        try (final FileOutputStream outstream = new FileOutputStream(trustStoreFile)) {
            trustStore.store(outstream, password);
        }
        // trust own CA and all self-signed certificates         
        final SSLContext sslContext = SSLContexts.custom()
                .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
        // allow trusted protocols only
        final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                new String[] { "SSLv2Hello", "TLSv1", "TLSv1.1", "TLSv1.2" }, null,
                new DefaultHostnameVerifier());
        httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    } catch (Exception e) {
        LOGGER.error("Failed to create HTTP client", e);
    }
    return httpClient;
}