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:be.bzbit.framework.spring.support.KeyStoreFactoryBean.java

public final void afterPropertiesSet() throws GeneralSecurityException, IOException {
    if (StringUtils.hasLength(provider) && StringUtils.hasLength(type)) {
        keyStore = KeyStore.getInstance(type, provider);
    } else if (StringUtils.hasLength(type)) {
        keyStore = KeyStore.getInstance(type);
    } else {// w  w  w  .j a  v  a  2 s  .  co  m
        keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    }
    InputStream is = null;
    try {
        if (location != null && location.exists()) {
            is = location.getInputStream();
            if (logger.isInfoEnabled()) {
                logger.info("Loading key store from " + location);
            }
        } else if (logger.isWarnEnabled()) {
            logger.warn("Creating empty key store");
        }
        keyStore.load(is, password);
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

From source file:com.lhtechnologies.DoorApp.AuthenticatorService.java

@Override
protected void onHandleIntent(Intent intent) {
    if (intent.getAction().equals(stopAction)) {
        stopSelf();/*ww w. ja v  a2 s .  com*/
    } else if (intent.getAction().equals(authenticateAction)) {
        //Check if we want to open the front door or flat door
        String doorToOpen = FrontDoor;
        String authCode = null;
        if (intent.hasExtra(FlatDoor)) {
            doorToOpen = FlatDoor;
            authCode = intent.getCharSequenceExtra(FlatDoor).toString();
        }

        if (intent.hasExtra(LetIn)) {
            doorToOpen = LetIn;
        }

        //Now run the connection code (Hope it runs asynchronously and we do not need AsyncTask --- NOPE --YES
        urlConnection = null;
        URL url;

        //Prepare the return intent
        Intent broadcastIntent = new Intent(AuthenticationFinishedBroadCast);

        try {
            //Try to create the URL, return an error if it fails
            url = new URL(address);

            if (!url.getProtocol().equals("https")) {
                throw new MalformedURLException("Please only use https protocol!");
            }

            String password = "password";
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(getResources().getAssets().open("LH Technologies Root CA.bks"),
                    password.toCharArray());

            TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
            tmf.init(keyStore);

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

            urlConnection = (HttpsURLConnection) url.openConnection();
            urlConnection.setSSLSocketFactory(context.getSocketFactory());
            urlConnection.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
            urlConnection.setConnectTimeout(15000);
            urlConnection.setRequestMethod("POST");

            urlConnection.setDoOutput(true);
            urlConnection.setChunkedStreamingMode(0);

            OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());

            //Write our stuff to the output stream;
            out.write("deviceName=" + deviceName + "&udid=" + udid + "&secret=" + secret + "&clientVersion="
                    + clientVersion + "&doorToOpen=" + doorToOpen);
            if (doorToOpen.equals(FlatDoor)) {
                out.write("&authCode=" + authCode);
                //Put an extra in so the return knows we opened the flat door
                broadcastIntent.putExtra(FlatDoor, FlatDoor);
            }

            out.close();

            BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));

            //Read the answer
            String decodedString;
            String returnString = "";
            while ((decodedString = in.readLine()) != null) {
                returnString += decodedString;
            }
            in.close();

            broadcastIntent.putExtra(AuthenticatorReturnCode, returnString);

        } catch (MalformedURLException e) {
            broadcastIntent.putExtra(AuthenticatorReturnCode, ClientErrorMalformedURL);
        } catch (Exception e) {
            broadcastIntent.putExtra(AuthenticatorReturnCode, ClientErrorUndefined);
            broadcastIntent.putExtra(AuthenticatorErrorDescription, e.getLocalizedMessage());
        } finally {
            if (urlConnection != null)
                urlConnection.disconnect();
            //Now send a broadcast with the result
            sendOrderedBroadcast(broadcastIntent, null);
            Log.e(this.getClass().getSimpleName(), "Send Broadcast!");
        }
    }

}

From source file:com.openmeap.util.SSLUtils.java

public static KeyStore loadKeyStore(InputStream keyStoreStream, String password)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {

    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(keyStoreStream, password.toCharArray());
    return ks;// w w w  .  j a v  a2  s.  c o m
}

From source file:sample.tomcat.SslApplicationTests.java

private SSLSocketFactory secureSocketFactory() throws Exception {
    KeyStore truststore = KeyStore.getInstance(KeyStore.getDefaultType());
    truststore.load(getKeyStoreFile(), "password".toCharArray());
    // setup ssl context
    SSLContext ctx = SSLContexts.custom().loadTrustMaterial(truststore)
            .loadKeyMaterial(truststore, "password".toCharArray()).build();
    return ctx.getSocketFactory();
}

From source file:com.xyproto.archfriend.Web.java

private HttpClient getNewHttpClient() {
    try {/*from   w  ww.jav  a  2s . c o  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.wialon.remote.ApacheSdkHttpClient.java

private void initDefaultClient() {
    BasicHttpParams httpParams = getBasicHttpParams(DEFAULT_SOCKET_TIMEOUT);
    KeyStore trustStore;// ww  w. j av a  2  s. c  om
    SSLSocketFactory sf = null;
    try {
        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        sf = new TrustAllSSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } catch (Exception e) {
        e.printStackTrace();
    }
    registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    if (sf != null)
        registry.register(new Scheme("https", sf, 443));
    ThreadSafeClientConnManager clientConnectionManager = new ThreadSafeClientConnManager(httpParams, registry);
    defaultHttpClient = new DefaultHttpClient(clientConnectionManager, httpParams);
}

From source file:org.apache.ranger.common.PropertiesUtil.java

@Override
protected void processProperties(ConfigurableListableBeanFactory beanFactory, Properties props)
        throws BeansException {

    // First let's add the system properties
    Set<Object> keySet = System.getProperties().keySet();
    for (Object key : keySet) {
        String keyStr = key.toString();
        propertiesMap.put(keyStr, System.getProperties().getProperty(keyStr).trim());
    }/*  w  w  w . j a  v  a 2s . co m*/

    // Let's add our properties now
    keySet = props.keySet();
    for (Object key : keySet) {
        String keyStr = key.toString();
        propertiesMap.put(keyStr, props.getProperty(keyStr).trim());
    }

    // update system trust store path with custom trust store.
    if (propertiesMap != null && propertiesMap.containsKey("ranger.truststore.file")) {
        if (!StringUtils.isEmpty(propertiesMap.get("ranger.truststore.file"))) {
            System.setProperty("javax.net.ssl.trustStore", propertiesMap.get("ranger.truststore.file"));
            System.setProperty("javax.net.ssl.trustStoreType", KeyStore.getDefaultType());
            Path trustStoreFile = Paths.get(propertiesMap.get("ranger.truststore.file"));
            if (!Files.exists(trustStoreFile) || !Files.isReadable(trustStoreFile)) {
                logger.debug("Could not find or read truststore file '"
                        + propertiesMap.get("ranger.truststore.file") + "'");
            } else {
                if (propertiesMap != null && propertiesMap.containsKey("ranger.credential.provider.path")) {
                    String path = propertiesMap.get("ranger.credential.provider.path");
                    String trustStoreAlias = getProperty("ranger.truststore.alias", "trustStoreAlias");
                    if (path != null && trustStoreAlias != null) {
                        String trustStorePassword = CredentialReader.getDecryptedString(path.trim(),
                                trustStoreAlias.trim());
                        if (trustStorePassword != null && !trustStorePassword.trim().isEmpty()
                                && !trustStorePassword.trim().equalsIgnoreCase("none")) {
                            propertiesMap.put("ranger.truststore.password", trustStorePassword);
                            props.put("ranger.truststore.password", trustStorePassword);
                        } else {
                            logger.info(
                                    "trustStorePassword password not applied; clear text password shall be applicable");
                        }
                    }
                }
            }
        }
        System.setProperty("javax.net.ssl.trustStorePassword", propertiesMap.get("ranger.truststore.password"));
    }

    // update system key store path with custom key store.
    if (propertiesMap != null && propertiesMap.containsKey("ranger.keystore.file")) {
        if (!StringUtils.isEmpty(propertiesMap.get("ranger.keystore.file"))) {
            System.setProperty("javax.net.ssl.keyStore", propertiesMap.get("ranger.keystore.file"));
            System.setProperty("javax.net.ssl.keyStoreType", KeyStore.getDefaultType());
            Path keyStoreFile = Paths.get(propertiesMap.get("ranger.keystore.file"));
            if (!Files.exists(keyStoreFile) || !Files.isReadable(keyStoreFile)) {
                logger.debug("Could not find or read keystore file '"
                        + propertiesMap.get("ranger.keystore.file") + "'");
            } else {
                if (propertiesMap != null && propertiesMap.containsKey("ranger.credential.provider.path")) {
                    String path = propertiesMap.get("ranger.credential.provider.path");
                    String keyStoreAlias = getProperty("ranger.keystore.alias", "keyStoreAlias");
                    if (path != null && keyStoreAlias != null) {
                        String keyStorePassword = CredentialReader.getDecryptedString(path.trim(),
                                keyStoreAlias.trim());
                        if (keyStorePassword != null && !keyStorePassword.trim().isEmpty()
                                && !keyStorePassword.trim().equalsIgnoreCase("none")) {
                            propertiesMap.put("ranger.keystore.password", keyStorePassword);
                            props.put("ranger.keystore.password", keyStorePassword);
                        } else {
                            logger.info(
                                    "keyStorePassword password not applied; clear text password shall be applicable");
                        }
                    }
                }
            }
        }
        System.setProperty("javax.net.ssl.keyStorePassword", propertiesMap.get("ranger.keystore.password"));
    }

    //update unixauth keystore and truststore credentials
    if (propertiesMap != null && propertiesMap.containsKey("ranger.credential.provider.path")) {
        String path = propertiesMap.get("ranger.credential.provider.path");
        if (path != null) {
            String unixAuthKeyStoreAlias = getProperty("ranger.unixauth.keystore.alias",
                    "unixAuthKeyStoreAlias");
            if (unixAuthKeyStoreAlias != null) {
                String unixAuthKeyStorePass = CredentialReader.getDecryptedString(path.trim(),
                        unixAuthKeyStoreAlias.trim());
                if (unixAuthKeyStorePass != null && !unixAuthKeyStorePass.trim().isEmpty()
                        && !unixAuthKeyStorePass.trim().equalsIgnoreCase("none")) {
                    propertiesMap.put("ranger.unixauth.keystore.password", unixAuthKeyStorePass);
                    props.put("ranger.unixauth.keystore.password", unixAuthKeyStorePass);
                } else {
                    logger.info(
                            "unixauth keystore password not applied; clear text password shall be applicable");
                }
            }
            //
            String unixAuthTrustStoreAlias = getProperty("ranger.unixauth.truststore.alias",
                    "unixAuthTrustStoreAlias");
            if (unixAuthTrustStoreAlias != null) {
                String unixAuthTrustStorePass = CredentialReader.getDecryptedString(path.trim(),
                        unixAuthTrustStoreAlias.trim());
                if (unixAuthTrustStorePass != null && !unixAuthTrustStorePass.trim().isEmpty()
                        && !unixAuthTrustStorePass.trim().equalsIgnoreCase("none")) {
                    propertiesMap.put("ranger.unixauth.truststore.password", unixAuthTrustStorePass);
                    props.put("ranger.unixauth.truststore.password", unixAuthTrustStorePass);
                } else {
                    logger.info(
                            "unixauth truststore password not applied; clear text password shall be applicable");
                }
            }
        }
    }

    //update credential from keystore
    if (propertiesMap != null && propertiesMap.containsKey("ranger.credential.provider.path")
            && propertiesMap.containsKey("ranger.jpa.jdbc.credential.alias")) {
        String path = propertiesMap.get("ranger.credential.provider.path");
        String alias = propertiesMap.get("ranger.jpa.jdbc.credential.alias");
        if (path != null && alias != null) {
            String xaDBPassword = CredentialReader.getDecryptedString(path.trim(), alias.trim());
            if (xaDBPassword != null && !xaDBPassword.trim().isEmpty()
                    && !"none".equalsIgnoreCase(xaDBPassword.trim())) {
                propertiesMap.put("ranger.jpa.jdbc.password", xaDBPassword);
                props.put("ranger.jpa.jdbc.password", xaDBPassword);
            } else {
                logger.info(
                        "Credential keystore password not applied for Ranger DB; clear text password shall be applicable");
            }
        }
    }
    if (propertiesMap != null && propertiesMap.containsKey("ranger.credential.provider.path")
            && propertiesMap.containsKey("ranger.jpa.audit.jdbc.credential.alias")) {
        String path = propertiesMap.get("ranger.credential.provider.path");
        String alias = propertiesMap.get("ranger.jpa.audit.jdbc.credential.alias");
        if (path != null && alias != null) {
            String auditDBPassword = CredentialReader.getDecryptedString(path.trim(), alias.trim());
            if (auditDBPassword != null && !auditDBPassword.trim().isEmpty()
                    && !"none".equalsIgnoreCase(auditDBPassword.trim())) {
                propertiesMap.put("ranger.jpa.audit.jdbc.password", auditDBPassword);
                props.put("ranger.jpa.audit.jdbc.password", auditDBPassword);
            } else {
                logger.info(
                        "Credential keystore password not applied for Audit DB; clear text password shall be applicable");
            }
        }
    }
    if (propertiesMap != null && propertiesMap.containsKey("ranger.authentication.method")) {
        String authenticationMethod = propertiesMap.get("ranger.authentication.method");
        if (authenticationMethod != null && ("ACTIVE_DIRECTORY".equalsIgnoreCase(authenticationMethod)
                || "AD".equalsIgnoreCase(authenticationMethod))) {
            if (propertiesMap != null && propertiesMap.containsKey("ranger.credential.provider.path")
                    && propertiesMap.containsKey("ranger.ldap.ad.binddn.credential.alias")) {
                String path = propertiesMap.get("ranger.credential.provider.path");
                String alias = propertiesMap.get("ranger.ldap.ad.binddn.credential.alias");
                if (path != null && alias != null) {
                    String bindDNPassword = CredentialReader.getDecryptedString(path.trim(), alias.trim());
                    if (bindDNPassword != null && !bindDNPassword.trim().isEmpty()
                            && !"none".equalsIgnoreCase(bindDNPassword.trim())) {
                        propertiesMap.put("ranger.ldap.ad.bind.password", bindDNPassword);
                        props.put("ranger.ldap.ad.bind.password", bindDNPassword);
                    } else {
                        logger.info(
                                "Credential keystore password not applied for AD Bind DN; clear text password shall be applicable");
                    }
                }
            }
        }
    }
    if (propertiesMap != null && propertiesMap.containsKey("ranger.authentication.method")) {
        String authenticationMethod = propertiesMap.get("ranger.authentication.method");
        if (authenticationMethod != null && ("LDAP".equalsIgnoreCase(authenticationMethod))) {
            if (propertiesMap != null && propertiesMap.containsKey("ranger.credential.provider.path")
                    && propertiesMap.containsKey("ranger.ldap.binddn.credential.alias")) {
                String path = propertiesMap.get("ranger.credential.provider.path");
                String alias = propertiesMap.get("ranger.ldap.binddn.credential.alias");
                if (path != null && alias != null) {
                    String bindDNPassword = CredentialReader.getDecryptedString(path.trim(), alias.trim());
                    if (bindDNPassword != null && !bindDNPassword.trim().isEmpty()
                            && !"none".equalsIgnoreCase(bindDNPassword.trim())) {
                        propertiesMap.put("ranger.ldap.bind.password", bindDNPassword);
                        props.put("ranger.ldap.bind.password", bindDNPassword);
                    } else {
                        logger.info(
                                "Credential keystore password not applied for LDAP Bind DN; clear text password shall be applicable");
                    }
                }
            }
        }
    }
    if (propertiesMap != null && propertiesMap.containsKey("ranger.audit.source.type")) {
        String auditStore = propertiesMap.get("ranger.audit.source.type");
        if (auditStore != null && ("solr".equalsIgnoreCase(auditStore))) {
            if (propertiesMap != null && propertiesMap.containsKey("ranger.credential.provider.path")
                    && propertiesMap.containsKey("ranger.solr.audit.credential.alias")) {
                String path = propertiesMap.get("ranger.credential.provider.path");
                String alias = propertiesMap.get("ranger.solr.audit.credential.alias");
                if (path != null && alias != null) {
                    String solrAuditPassword = CredentialReader.getDecryptedString(path.trim(), alias.trim());
                    if (solrAuditPassword != null && !solrAuditPassword.trim().isEmpty()
                            && !"none".equalsIgnoreCase(solrAuditPassword.trim())) {
                        propertiesMap.put("ranger.solr.audit.user.password", solrAuditPassword);
                        props.put("ranger.solr.audit.user.password", solrAuditPassword);
                    } else {
                        logger.info(
                                "Credential keystore password not applied for Solr; clear text password shall be applicable");
                    }
                }
            }
        }
    }
    if (propertiesMap != null) {
        String sha256PasswordUpdateDisable = "false";
        if (propertiesMap.containsKey("ranger.sha256Password.update.disable")) {
            sha256PasswordUpdateDisable = propertiesMap.get("ranger.sha256Password.update.disable");
            if (sha256PasswordUpdateDisable == null || sha256PasswordUpdateDisable.trim().isEmpty()
                    || !"true".equalsIgnoreCase(sha256PasswordUpdateDisable)) {
                sha256PasswordUpdateDisable = "false";
            }
        }
        propertiesMap.put("ranger.sha256Password.update.disable", sha256PasswordUpdateDisable);
        props.put("ranger.sha256Password.update.disable", sha256PasswordUpdateDisable);
    }
    if (RangerBizUtil.getDBFlavor() == AppConstants.DB_FLAVOR_MYSQL) {
        if (propertiesMap != null && propertiesMap.containsKey("ranger.db.ssl.enabled")) {
            String db_ssl_enabled = propertiesMap.get("ranger.db.ssl.enabled");
            if (StringUtils.isEmpty(db_ssl_enabled) || !"true".equalsIgnoreCase(db_ssl_enabled)) {
                db_ssl_enabled = "false";
            }
            db_ssl_enabled = db_ssl_enabled.toLowerCase();
            if ("true".equalsIgnoreCase(db_ssl_enabled)) {
                String db_ssl_required = propertiesMap.get("ranger.db.ssl.required");
                if (StringUtils.isEmpty(db_ssl_required) || !"true".equalsIgnoreCase(db_ssl_required)) {
                    db_ssl_required = "false";
                }
                db_ssl_required = db_ssl_required.toLowerCase();
                String db_ssl_verifyServerCertificate = propertiesMap
                        .get("ranger.db.ssl.verifyServerCertificate");
                if (StringUtils.isEmpty(db_ssl_verifyServerCertificate)
                        || !"true".equalsIgnoreCase(db_ssl_verifyServerCertificate)) {
                    db_ssl_verifyServerCertificate = "false";
                }
                db_ssl_verifyServerCertificate = db_ssl_verifyServerCertificate.toLowerCase();
                propertiesMap.put("ranger.db.ssl.enabled", db_ssl_enabled);
                props.put("ranger.db.ssl.enabled", db_ssl_enabled);
                propertiesMap.put("ranger.db.ssl.required", db_ssl_required);
                props.put("ranger.db.ssl.required", db_ssl_required);
                propertiesMap.put("ranger.db.ssl.verifyServerCertificate", db_ssl_verifyServerCertificate);
                props.put("ranger.db.ssl.verifyServerCertificate", db_ssl_verifyServerCertificate);
                String ranger_jpa_jdbc_url = propertiesMap.get("ranger.jpa.jdbc.url");
                if (!StringUtils.isEmpty(ranger_jpa_jdbc_url)) {
                    StringBuffer ranger_jpa_jdbc_url_ssl = new StringBuffer(ranger_jpa_jdbc_url);
                    ranger_jpa_jdbc_url_ssl.append("?useSSL=" + db_ssl_enabled + "&requireSSL="
                            + db_ssl_required + "&verifyServerCertificate=" + db_ssl_verifyServerCertificate);
                    propertiesMap.put("ranger.jpa.jdbc.url", ranger_jpa_jdbc_url_ssl.toString());
                    props.put("ranger.jpa.jdbc.url", ranger_jpa_jdbc_url_ssl.toString());
                    logger.info("ranger.jpa.jdbc.url=" + ranger_jpa_jdbc_url_ssl.toString());
                }
            }
        }
    }
    super.processProperties(beanFactory, props);
}

From source file:org.gw2InfoViewer.factories.HttpsConnectionFactory.java

public static HttpClient getHttpsClient(Certificate[] sslCertificate) {
    DefaultHttpClient httpClient;// w ww .  j  a  v a 2 s.c  om

    httpClient = new DefaultHttpClient();
    try {
        TrustManagerFactory tf = TrustManagerFactory.getInstance("X509");
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(null);
        for (int i = 0; i < sslCertificate.length; i++) {
            ks.setCertificateEntry("StartCom" + i, sslCertificate[i]);
        }

        tf.init(ks);
        TrustManager[] tm = tf.getTrustManagers();

        SSLContext sslCon = SSLContext.getInstance("SSL");
        sslCon.init(null, tm, new SecureRandom());
        SSLSocketFactory socketFactory = new SSLSocketFactory(ks);
        Scheme sch = new Scheme("https", 443, socketFactory);

        httpClient.getConnectionManager().getSchemeRegistry().register(sch);
    } catch (CertificateException | NoSuchAlgorithmException | KeyStoreException | IOException
            | KeyManagementException | UnrecoverableKeyException ex) {
        Logger.getLogger(HttpsConnectionFactory.class.getName()).log(Level.SEVERE, null, ex);
    }

    return httpClient;
}

From source file:com.android.volley.toolbox.https.SslHttpClient.java

@Override
protected ClientConnectionManager createClientConnectionManager() {
    SchemeRegistry registry = new SchemeRegistry();

    PlainSocketFactory pfs = PlainSocketFactory.getSocketFactory();
    Scheme s = new Scheme(HTTP_SCHEME, pfs, HTTP_DEFAULT_PORT);
    registry.register(s);/*from w w  w .j a va 2 s.c  o  m*/

    ThreadSafeClientConnManager ret = null;
    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        registry.register(new Scheme(HTTP_SSL_SCHEME, sf, mHttpsPort));

        ret = new ThreadSafeClientConnManager(new BasicHttpParams(), registry);
    } catch (GeneralSecurityException e) {
        throw new IllegalStateException(e);
    } catch (IOException e) {
        e.printStackTrace();
    }

    return ret;
}

From source file:com.shekhargulati.reactivex.rxokhttp.SslCertificates.java

private SslCertificates(final Builder builder) throws SslCertificateException {
    if ((builder.caCertPath == null) || (builder.clientCertPath == null) || (builder.clientKeyPath == null)) {
        throw new SslCertificateException(
                "caCertPath, clientCertPath, and clientKeyPath must all be specified");
    }/*www. ja  v a  2s  . co m*/

    try {
        final CertificateFactory cf = CertificateFactory.getInstance("X.509");
        final Certificate caCert = cf.generateCertificate(Files.newInputStream(builder.caCertPath));
        final Certificate clientCert = cf.generateCertificate(Files.newInputStream(builder.clientCertPath));

        final PEMKeyPair clientKeyPair = (PEMKeyPair) new PEMParser(
                Files.newBufferedReader(builder.clientKeyPath, Charset.defaultCharset())).readObject();

        final PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(
                clientKeyPair.getPrivateKeyInfo().getEncoded());
        final KeyFactory kf = KeyFactory.getInstance("RSA");
        final PrivateKey clientKey = kf.generatePrivate(spec);

        final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        trustStore.setEntry("ca", new KeyStore.TrustedCertificateEntry(caCert), null);

        final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, KEY_STORE_PASSWORD);
        keyStore.setCertificateEntry("client", clientCert);
        keyStore.setKeyEntry("key", clientKey, KEY_STORE_PASSWORD, new Certificate[] { clientCert });

        this.sslContext = SSLContexts.custom().loadTrustMaterial(trustStore)
                .loadKeyMaterial(keyStore, KEY_STORE_PASSWORD).useTLS().build();
    } catch (java.security.cert.CertificateException | IOException | NoSuchAlgorithmException
            | InvalidKeySpecException | KeyStoreException | UnrecoverableKeyException
            | KeyManagementException e) {
        throw new SslCertificateException(e);
    }
}