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:com.pispower.video.sdk.net.SimpleSSLSocketFactory.java

/**
 * Gets a DefaultHttpClient which trusts a set of certificates specified by
 * the KeyStore/*  w w w.  j a va2  s  . c o  m*/
 * 
 * @param keyStore
 *            custom provided KeyStore instance
 * @return DefaultHttpClient
 */
public static DefaultHttpClient getDefaultHttpClient() {

    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        SSLSocketFactory sf = new SimpleSSLSocketFactory(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));

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

        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

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

From source file:com.example.wechatsample.library.http.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient.// w w  w.j  ava2  s .  c o  m
 */
public AsyncHttpClient() {
    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, socketTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

    HttpConnectionParams.setSoTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(httpParams,
            String.format("android-async-http/%s (http://loopj.com/android-async-http)", VERSION));
    ThreadSafeClientConnManager cm = null;
    try {
        //  https?
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); // ??

        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        schemeRegistry.register(new Scheme("https", sf, 443));
        schemeRegistry.register(new Scheme("https", sf, 8443));
        cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
                request.addHeader(header, clientHeaderMap.get(header));
            }
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
                return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                        response.setEntity(new InflatingEntity(response.getEntity()));
                        break;
                    }
                }
            }
        }
    });

    httpClient.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES));

    threadPool = (ThreadPoolExecutor) Executors.newCachedThreadPool();

    requestMap = new WeakHashMap<Context, List<WeakReference<Future<?>>>>();
    clientHeaderMap = new HashMap<String, String>();
}

From source file:org.wso2.carbon.security.util.ServerCrypto.java

public ServerCrypto(Properties prop, ClassLoader loader) throws CredentialException, IOException {

    try {/*  ww w .ja v a 2  s  .c o  m*/

        int tenantId;

        String tenantIdString = (String) prop.get(PROP_ID_TENANT_ID);

        if (tenantIdString == null || tenantIdString.trim().length() == 0) {
            tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
        } else {
            tenantId = new Integer(tenantIdString);
        }

        registry = SecurityServiceHolder.getRegistryService().getGovernanceSystemRegistry(tenantId);

        this.properties = prop;

        KeyStoreManager keyMan = KeyStoreManager.getInstance(tenantId);
        String ksId = this.properties.getProperty(PROP_ID_PRIVATE_STORE);
        if (ksId != null) {
            this.keystore = keyMan.getKeyStore(ksId);
        }

        // Get other keystores if available
        String trustStoreIds = this.properties.getProperty(PROP_ID_TRUST_STORES);
        if (trustStoreIds != null && trustStoreIds.trim().length() != 0) {
            String[] ids = trustStoreIds.trim().split(",");
            this.trustStores = new ArrayList(ids.length);
            for (int i = 0; i < ids.length; i++) {
                String id = ids[i];
                KeyStore tstks = keyMan.getKeyStore(id);
                this.trustStores.add(i, tstks);
            }
        }
    } catch (Exception e) {
        log.error("error creating ServerCryto", e);
        throw new CredentialException(3, "secError00", e);
    }

    /**
     * Load cacerts
     */
    String cacertsPath = System.getProperty("java.home") + "/lib/security/cacerts";
    InputStream cacertsIs = new FileInputStream(cacertsPath);
    try {
        String cacertsPasswd = properties.getProperty(PROP_ID_CACERT_PASS, "changeit");
        cacerts = KeyStore.getInstance(KeyStore.getDefaultType());
        cacerts.load(cacertsIs, cacertsPasswd.toCharArray());

    } catch (GeneralSecurityException e) {
        log.warn("Unable load to cacerts from the JDK.", e);
        if (CollectionUtils.isNotEmpty(trustStores)) {
            cacerts = this.trustStores.get(0);
        } else {
            throw new CredentialException(3, "secError00", e);
        }
    } finally {
        cacertsIs.close();
    }

}

From source file:mixedserver.protocol.jsonrpc.client.HTTPSession.java

HttpClient http() throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException,
        KeyStoreException, CertificateException, IOException {
    if (client == null) {
        HttpParams params = new BasicHttpParams();

        HttpConnectionParams.setConnectionTimeout(params, getConnectionTimeout());
        HttpConnectionParams.setSoTimeout(params, getSoTimeout());
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);//from  ww w.  j a  v  a 2 s. c o m

        SSLSocketFactory sf = new EasySSLSocketFactory(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 mgr = new ThreadSafeClientConnManager(
         * params, registry);
         */

        ClientConnectionManager mgr = new ThreadSafeClientConnManager(params, registry);

        DefaultHttpClient defaultHttpClient = new DefaultHttpClient(mgr, params);

        // gzip?
        defaultHttpClient.addRequestInterceptor(new HttpRequestInterceptor() {

            public void process(final HttpRequest request, final HttpContext context)
                    throws HttpException, IOException {
                if (!request.containsHeader("Accept-Encoding")) {
                    request.addHeader("Accept-Encoding", "gzip");
                }
            }

        });

        defaultHttpClient.addResponseInterceptor(new HttpResponseInterceptor() {

            public void process(final HttpResponse response, final HttpContext context)
                    throws HttpException, IOException {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    Header ceheader = entity.getContentEncoding();
                    if (ceheader != null) {
                        HeaderElement[] codecs = ceheader.getElements();
                        for (int i = 0; i < codecs.length; i++) {
                            if (codecs[i].getName().equalsIgnoreCase("gzip")) {
                                response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                                return;
                            }
                        }
                    }
                }
            }

        });
        client = defaultHttpClient;
    }
    return client;
}

From source file:view.CertificateManagementDialog.java

private KeyStore isValidKeystore(File file, boolean showDialog) {
    FileInputStream is = null;//from  ww w. j a v a2  s  .  co m
    try {
        is = new FileInputStream(file);
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(is, null);
        if (ks.aliases().hasMoreElements()) {
            return ks;
        } else {
            if (showDialog) {
                JOptionPane.showMessageDialog(this, Bundle.getBundle().getString("emptyChain"), "",
                        JOptionPane.INFORMATION_MESSAGE);
            }
            return ks;
        }
    } catch (java.security.cert.CertificateException | NoSuchAlgorithmException | KeyStoreException
            | FileNotFoundException e) {
        if (showDialog) {
            JOptionPane.showMessageDialog(this, Bundle.getBundle().getString("fileNotKeystoreOrCorrupted"), "",
                    JOptionPane.ERROR_MESSAGE);
        }
        return null;
    } catch (IOException e) {
        if (showDialog) {
            JOptionPane.showMessageDialog(this, Bundle.getBundle().getString("fileNotKeystoreOrCorrupted"), "",
                    JOptionPane.ERROR_MESSAGE);
        }
        return null;
    } finally {
        if (null != is) {
            try {
                is.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:mobi.dlys.android.core.net.http.client.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient./*from   ww w. j  av a2 s.c o  m*/
 * 
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 * @throws KeyStoreException
 * @throws UnrecoverableKeyException
 */
public AsyncHttpClient()
        throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, socketTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

    HttpConnectionParams.setSoTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(httpParams,
            String.format("android-async-http/%s (http://loopj.com/android-async-http)", VERSION));

    KeyStore keyStroe = KeyStore.getInstance(KeyStore.getDefaultType());
    SSLSocketFactory ssf = new ClientSSLSocketFactory(keyStroe);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", ssf, 443));
    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
                request.addHeader(header, clientHeaderMap.get(header));
            }
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
                return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                        response.setEntity(new InflatingEntity(response.getEntity()));
                        break;
                    }
                }
            }
        }
    });

    httpClient.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES));

    // threadPool = (ThreadPoolExecutor) Executors.newCachedThreadPool();
    threadPool = ThreadPool.getInstance().getDefaultThreadPoolExecutor();

    // threadPool = new ThreadPoolExecutor(10, 30, 60, TimeUnit.SECONDS, new
    // LinkedBlockingQueue<Runnable>());

    requestMap = new WeakHashMap<Context, List<WeakReference<Future<?>>>>();
    clientHeaderMap = new HashMap<String, String>();
}

From source file:org.wso2.carbon.webapp.ext.cxf.crypto.CXFServerCrypto.java

public CXFServerCrypto(Properties prop, ClassLoader loader) throws CredentialException, IOException {
    super(prop);/*from  w w w . java 2  s  .co  m*/
    try {

        String tenantIdString = (String) prop.get(PROP_ID_TENANT_ID);
        tenantDomain = (String) prop.get(PROP_ID_TENANT_DOMAIN);

        if (tenantIdString == null || tenantIdString.trim().length() == 0) {
            tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
            tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
        } else {
            //ignore
        }

        registry = ((RegistryService) PrivilegedCarbonContext.getThreadLocalCarbonContext()
                .getOSGiService(org.wso2.carbon.registry.core.service.RegistryService.class))
                        .getGovernanceSystemRegistry(tenantId);
        keyAdmin = new KeyStoreAdmin(tenantId, registry);
        this.properties = prop;

        keyMan = KeyStoreManager.getInstance(tenantId);
        if (tenantId == MultitenantConstants.SUPER_TENANT_ID) {
            this.keystore = keyMan.getPrimaryKeyStore();
        } else {
            this.keystore = keyMan.getKeyStore(generateKSNameFromDomainName(tenantDomain));
        }

        // Get other keystores if available
        String trustStoreIds = this.properties.getProperty(PROP_ID_TRUST_STORES);
        if (trustStoreIds != null && trustStoreIds.trim().length() != 0) {
            String[] ids = trustStoreIds.trim().split(",");
            this.trustStores = new ArrayList(ids.length);
            for (int i = 0; i < ids.length; i++) {
                String id = ids[i];
                KeyStore tstks = keyMan.getKeyStore(id);
                this.trustStores.add(i, tstks);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        log.error("error creating CXFServerCryto", e);
        throw new CredentialException(3, "secError00", e);
    }

    /**
     * Load cacerts
     */
    String cacertsPath = System.getProperty("java.home") + "/lib/security/cacerts";
    InputStream cacertsIs = new FileInputStream(cacertsPath);
    try {
        String cacertsPasswd = properties.getProperty(PROP_ID_CACERT_PASS, "changeit");
        cacerts = KeyStore.getInstance(KeyStore.getDefaultType());
        cacerts.load(cacertsIs, cacertsPasswd.toCharArray());

    } catch (GeneralSecurityException e) {
        log.warn("Unable load to cacerts from the JDK.");
        if (trustStores != null && trustStores.size() > 0) {
            cacerts = this.trustStores.get(0);
        } else {
            throw new CredentialException(3, "secError00", e);
        }
    } finally {
        cacertsIs.close();
    }

}

From source file:org.votingsystem.util.HttpHelper.java

private HttpHelper() {
    try {// ww  w .ja  v a 2 s  .  co  m
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        SSLContext sslcontext = null;
        SSLConnectionSocketFactory sslsf = null;
        if (ContextVS.getInstance().getVotingSystemSSLCerts() != null) {
            log.info("loading SSLContext with app certificates");
            X509Certificate sslServerCert = ContextVS.getInstance().getVotingSystemSSLCerts().iterator().next();
            trustStore.setCertificateEntry(sslServerCert.getSubjectDN().toString(), sslServerCert);
            sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore).build();
            X509HostnameVerifier hostnameVerifier = (X509HostnameVerifier) new AllowAllHostnameVerifier();
            sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null,
                    hostnameVerifier);
        } else {
            sslcontext = SSLContexts.createSystemDefault();
            sslsf = new SSLConnectionSocketFactory(sslcontext);
            log.info("loading default SSLContext");
        }
        // Create a registry of custom connection socket factories for supported protocol schemes.
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                .<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.INSTANCE)
                .register("https", sslsf).build();
        //Create socket configuration
        //SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).build();
        //Configure the connection manager to use socket configuration either by default or for a specific host.
        //connManager.setDefaultSocketConfig(socketConfig);
        connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry, connFactory, dnsResolver);
        connManager.setMaxTotal(200);
        connManager.setDefaultMaxPerRoute(100);
        connEvictor = new IdleConnectionEvictor(connManager);
        connEvictor.start();
        HttpRoute httpRouteVS = new HttpRoute(new HttpHost("www.sistemavotacion.org", 80));
        connManager.setMaxPerRoute(httpRouteVS, 200);
        /* timeouts with large simulations ->
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(REQUEST_TIME_OUT)
            .setConnectionRequestTimeout(REQUEST_TIME_OUT).setSocketTimeout(REQUEST_TIME_OUT).build();
        httpClient = HttpClients.custom().setConnectionManager(connManager).setDefaultRequestConfig(
            requestConfig).build();*/
        httpClient = HttpClients.custom().setConnectionManager(connManager).build();
    } catch (Exception ex) {
        log.log(Level.SEVERE, ex.getMessage(), ex);
    }
}

From source file:com.eviware.soapui.impl.wsdl.support.wss.crypto.KeyMaterialWssCrypto.java

@NonNull
private String fileExtensionToKeystoreType(String fileExtension) {
    if (fileExtension.equals(PKCS12_FILE_EXTENSION)) {
        return PKCS12_KEYSTORE_TYPE;
    } else if (fileExtension.equals(JCEKS_FILE_EXTENSION)) {
        return JCEKS_KEYSTORE_TYPE;
    } else {//from w  w  w . j a  v a2 s  .c  om
        return KeyStore.getDefaultType();
    }
}